import express from 'express';
import morgan from 'morgan';
import helmet from 'helmet';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import dotenv from 'dotenv';
dotenv.config();

import { validateBody } from './middlewares/global/validateBody.js';
import { notFound } from './middlewares/global/notFound.js';
import { errorHandler } from './middlewares/global/errorHandler.js';
import { apiRateLimiter } from './middlewares/security/rateLimiter.js';

// Import routes
import authRoutes from './routes/auth.routes.js';
import adminRoutes from './routes/admin.routes.js';
import contactRoutes from './routes/contact.routes.js';
import crmEmailRoutes from './routes/crm-email.routes.js';
import emailAccountRoutes from './routes/email-account.routes.js';
import timesheetRoutes from './routes/timesheet.routes.js';
import companyRoutes from './routes/company.routes.js';
import projectRoutes from './routes/project.routes.js';
import todoRoutes from './routes/todo.routes.js';
import timeTrackingRoutes from './routes/time-tracking.routes.js';

const app = express();

// Security middleware
app.use(morgan('dev'));
app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        styleSrc: ["'self'", "'unsafe-inline'"],
      },
    },
    hsts: {
      maxAge: 31536000,
      includeSubDomains: true,
      preload: true,
    },
  })
);

// CORS configuration
const corsOptions = {
  origin: process.env.CORS_ORIGIN || 'http://localhost:5173',
  credentials: true,
  optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));

// Body parsing middleware
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use(cookieParser());

// Custom body validation middleware
app.use(validateBody);

// Rate limiting for all API routes
app.use('/api', apiRateLimiter);

// Health check endpoint
app.get('/health', (req, res) => {
  res.status(200).json({
    success: true,
    message: 'CRM API is running',
    timestamp: new Date().toISOString(),
  });
});

// API Routes
app.use('/api/auth', authRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/contacts', contactRoutes);
app.use('/api/emails', crmEmailRoutes);
app.use('/api/email-accounts', emailAccountRoutes);
app.use('/api/timesheets', timesheetRoutes);
app.use('/api/companies', companyRoutes);
app.use('/api/projects', projectRoutes);
app.use('/api/todos', todoRoutes);
app.use('/api/time-tracking', timeTrackingRoutes);

// Basic route
app.get('/', (req, res) => {
  res.json({
    success: true,
    message: 'CRM API Server',
    version: '1.0.0',
  });
});

// Global Middlewares (must be last)
app.use(notFound);
app.use(errorHandler);

export default app;
