require('dotenv').config();
const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const pool = require('./config/database');

// Import routes
const adminRoutes = require('./routes/adminRoutes');
// const adminRoutes = require('./routes/adminRoutes');
const userRoutes = require('./routes/userRoutes');
const activityLogRoutes = require('./routes/activityLogRoutes');
const notificationRoutes = require('./routes/notificationRoutes');

// Initialize Express app
const app = express();

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// CORS Configuration
app.use(cors({
  origin: function (origin, callback) {
    // Allow requests with no origin (like mobile apps or curl requests)
    if (!origin) return callback(null, true);

    // In development, allow all origins
    if (process.env.NODE_ENV === 'development') {
      return callback(null, true);
    }

    // In production, use whitelist
    const allowedOrigins = [
      'http://localhost:3000',
      'http://localhost:5000',
      'http://127.0.0.1:3000',
      'http://127.0.0.1:5000',
      process.env.CORS_ORIGIN,
    ];

    if (allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(null, false); // Silently reject in production
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
  optionsSuccessStatus: 200,
}));

// Handle preflight requests
app.options('*', cors());

app.use(cookieParser());

// Request logging middleware (optional)
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`);
  next();
});

// API Routes
const apiPrefix = process.env.API_PREFIX || '/api';

app.use(`${apiPrefix}/admin`, adminRoutes);
app.use(`${apiPrefix}/users`, userRoutes);
app.use(`${apiPrefix}/activity-logs`, activityLogRoutes);
app.use(`${apiPrefix}/notifications`, notificationRoutes);

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

// Root endpoint
app.get('/', (req, res) => {
  res.status(200).json({
    status: true,
    message: 'Numerology CMS Backend API',
    version: '1.0.0',
    endpoints: {
      health: `${apiPrefix}/health`,
      admin: {
        register: `POST ${apiPrefix}/admin/register`,
        login: `POST ${apiPrefix}/admin/login`,
        refresh: `POST ${apiPrefix}/admin/refresh`,
        logout: `POST ${apiPrefix}/admin/logout`,
        getAll: `GET ${apiPrefix}/admin`,
      },
      users: {
        getAll: `GET ${apiPrefix}/users?page=1&limit=10&search=keyword`,
        getById: `GET ${apiPrefix}/users/:id`,
        create: `POST ${apiPrefix}/users`,
        update: `PUT ${apiPrefix}/users/:id`,
        delete: `DELETE ${apiPrefix}/users/:id`,
        stats: `GET ${apiPrefix}/users/stats`,
      },
    },
  });
});

// 404 handler
app.use((req, res) => {
  res.status(404).json({
    status: false,
    message: 'Route not found',
    data: null,
  });
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(500).json({
    status: false,
    message: 'Internal server error',
    data: null,
    error: process.env.NODE_ENV === 'development' ? err.message : undefined,
  });
});

// Start server
const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
  console.log('\n' + '='.repeat(50));
  console.log('🚀 Numerology CMS Backend API');
  console.log('='.repeat(50));
  console.log(`✓ Server running on port ${PORT}`);
  console.log(`✓ Environment: ${process.env.NODE_ENV || 'development'}`);
  console.log(`✓ API Prefix: ${apiPrefix}`);
  console.log('='.repeat(50) + '\n');
});

// Handle graceful shutdown
process.on('SIGINT', () => {
  console.log('\n\nShutting down gracefully...');
  pool.end((err) => {
    if (err) {
      console.error('Error closing database pool:', err);
      process.exit(1);
    }
    console.log('Database pool closed');
    process.exit(0);
  });
});

module.exports = app;
