import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import pool from './config/db.js';

import authRoutes from './routes/auth.js';
import userRoutes from './routes/users.js';
import listingRoutes from './routes/listings.js';
import uploadRoutes from './routes/upload.js';
import reviewRoutes from './routes/reviews.js';
import overviewRoutes from './routes/overview.js';
import analyticsRoutes from './routes/analytics.js';
import taskRoutes from './routes/tasks.js';
import reportRoutes from './routes/reports.js';
import promotionRoutes from './routes/promotions.js';
import settingsRoutes from './routes/settings.js';

dotenv.config();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
const PORT = process.env.PORT || 5000;

// Trust proxy headers from cPanel / NGINX / Apache reverse proxy
app.set('trust proxy', 1);

// Permissive CORS for public directory access
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept', 'Origin'],
  credentials: false
}));
app.options('*', cors());

app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));

// Serve uploaded media files statically (relative to backend directory for cPanel/Passenger)
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { recursive: true });
}
app.use('/uploads', express.static(uploadsDir));

// Route Mounts
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/listings', listingRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/reviews', reviewRoutes);
app.use('/api/admin/overview', overviewRoutes);
app.use('/api/analytics', analyticsRoutes);
app.use('/api/admin/tasks', taskRoutes);
app.use('/api/admin/reports', reportRoutes);
app.use('/api/promotions', promotionRoutes);
app.use('/api/settings', settingsRoutes);

// Root Ping & Diagnostic Endpoints
app.get('/', (req, res) => {
  res.json({
    status: "online",
    service: "KHUJOUSA API Server",
    environment: process.env.NODE_ENV || "development",
    timestamp: new Date().toISOString()
  });
});

app.get('/api/health', async (req, res) => {
  let dbStatus = "connected";
  try {
    const [rows] = await pool.query('SELECT 1 as alive');
    if (!rows || rows.length === 0) dbStatus = "no response";
  } catch (err) {
    dbStatus = `disconnected (${err.message})`;
  }

  res.json({
    status: dbStatus.startsWith('connected') ? "healthy" : "degraded",
    database: dbStatus,
    uptime_seconds: Math.floor(process.uptime()),
    node_version: process.version,
    memory_usage_mb: Math.round(process.memoryUsage().rss / 1024 / 1024),
    timestamp: new Date().toISOString()
  });
});

// Start Server (supports both TCP port and Unix Domain Socket from CloudLinux Passenger)
const server = app.listen(PORT, () => {
  console.log(`[KHUJOUSA Server] Successfully bound to ${PORT} (PID: ${process.pid})`);
});

// Graceful shutdown for cPanel / Passenger process manager
process.on('SIGTERM', () => {
  console.log('[KHUJOUSA Server] SIGTERM received. Closing HTTP server gracefully...');
  server.close(() => {
    console.log('[KHUJOUSA Server] HTTP server closed.');
    pool.end();
  });
});

export default app;
