const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const nodemailer = require('nodemailer');
const moment = require('moment');

// Create Express app
const app = express();
const port = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

// Ensure directories exist
const dataDir = path.join(__dirname, 'data');
const logsDir = path.join(__dirname, 'logs');
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
if (!fs.existsSync(logsDir)) fs.mkdirSync(logsDir, { recursive: true });

// Simple logging
const logFile = path.join(logsDir, 'server.log');
const log = (message) => {
  const timestamp = new Date().toISOString();
  const logMessage = `[${timestamp}] ${message}\n`;
  console.log(logMessage);
  fs.appendFileSync(logFile, logMessage);
};

// Load environment variables
const dotenvPath = path.join(__dirname, '.env');
if (fs.existsSync(dotenvPath)) {
  require('dotenv').config({ path: dotenvPath });
  log('Environment variables loaded from .env file');
} else {
  log('No .env file found, using default environment variables');
}

// Routes
app.get('/api/status', (req, res) => {
  log('Status endpoint called');
  res.json({
    status: 'ok',
    version: '1.0.0',
    timestamp: new Date().toISOString(),
    environment: process.env.NODE_ENV || 'development'
  });
});

app.get('/api/emails', (req, res) => {
  log('Emails endpoint called');
  // Mock email data
  const emails = [
    {
      id: uuidv4(),
      from: 'john@example.com',
      to: 'support@smartinbox.com',
      subject: 'Hello from SmartINBOX',
      body: 'This is a test email from SmartINBOX.',
      date: new Date().toISOString()
    },
    {
      id: uuidv4(),
      from: 'jane@example.com',
      to: 'support@smartinbox.com',
      subject: 'Testing SmartINBOX',
      body: 'Just testing the SmartINBOX system.',
      date: new Date(Date.now() - 86400000).toISOString()
    },
    {
      id: uuidv4(),
      from: 'sales@company.com',
      to: 'info@smartinbox.com',
      subject: 'Business Proposal',
      body: 'We would like to discuss a business opportunity with you.',
      date: new Date(Date.now() - 172800000).toISOString()
    }
  ];
  res.json(emails);
});

app.post('/api/send-email', (req, res) => {
  log('Send email endpoint called');
  const { to, subject, body } = req.body;
  
  if (!to || !subject || !body) {
    return res.status(400).json({ error: 'Missing required fields' });
  }
  
  // In a real implementation, you would send the email here
  // For now, we'll just log it and return success
  log(`Email sent to ${to} with subject: ${subject}`);
  
  res.json({
    success: true,
    messageId: uuidv4(),
    timestamp: new Date().toISOString()
  });
});

app.get('/api/config', (req, res) => {
  log('Config endpoint called');
  res.json({
    appName: 'SmartINBOX',
    apiVersion: '1.0.0',
    features: {
      emailSending: true,
      emailReceiving: true,
      teamCollaboration: true,
      workflowManagement: true
    },
    limits: {
      maxAttachmentSize: 10 * 1024 * 1024, // 10MB
      maxEmailsPerDay: 1000
    }
  });
});

// Catch-all route for SPA
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// Start server
app.listen(port, () => {
  log(`Server running on port ${port}`);
  log(`Environment: ${process.env.NODE_ENV || 'development'}`);
  log(`Base URL: ${process.env.BASE_URL || 'http://localhost:' + port}`);
});