const express = require("express");
const app = express();
const dotenv = require("dotenv");
const cors = require("cors");
const session = require("express-session");

// Load environment variables BEFORE requiring passport config
dotenv.config();
const passport = require("./SAT_backend/src/config/passport");

const PORT = process.env.PORT || 5000;
/** All REST routes are mounted under this prefix (e.g. /api/sat/login). */
const API_PREFIX = "/api/sat";

// Log every request that hits this server (so we can see if login reaches the backend)
app.use((req, res, next) => {
  console.log('[SERVER]', req.method, req.originalUrl || req.url);
  next();
});

// Middlewares
app.use(cors({
  origin: process.env.FRONTEND_URL || 'http://localhost:3000',
  credentials: true
}));
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ extended: true, limit: "50mb" }));

// Session configuration for OAuth
app.use(
  session({
    secret: process.env.SESSION_SECRET || process.env.JWT_SECRET || 'your-session-secret',
    resave: false,
    saveUninitialized: false,
    cookie: {
      secure: process.env.NODE_ENV === 'production', // Use secure cookies in production (HTTPS)
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 1000 // 24 hours
    }
  })
);

// Initialize Passport
app.use(passport.initialize());
app.use(passport.session());

// Debug: log all incoming API requests (so we can see if login request reaches this server)
app.use(API_PREFIX, (req, res, next) => {
  console.log('[API]', req.method, req.originalUrl || req.url);
  next();
});

// Health check route
app.use(`${API_PREFIX}/health`, (req, res) => {
    return res.status(200).json({
        message: "Backend running successfully 🚀"
    });
});

// Import routes
const loginRoutes = require('./SAT_backend/src/routes/loginRoutes');
const accountStatusRoutes = require('./SAT_backend/src/routes/accountStatusRoutes');
const rolesRoutes = require('./SAT_backend/src/routes/rolesRoutes');
const departmentsRoutes = require('./SAT_backend/src/routes/departmentsRoutes');
const countryRoutes = require('./SAT_backend/src/routes/countryRoutes');
const auditStatusRoutes = require('./SAT_backend/src/routes/auditStatusRoutes');
const ticketsStatusRoutes = require('./SAT_backend/src/routes/ticketsStatusRoutes');
const ticketsTypeRoutes = require('./SAT_backend/src/routes/ticketsTypeRoutes');
const formsTypeRoutes = require('./SAT_backend/src/routes/formsTypeRoutes');
const questionTypeRoutes = require('./SAT_backend/src/routes/questionTypeRoutes');
const rpnRoutes = require('./SAT_backend/src/routes/rpnRoutes');
const locationsRoutes = require('./SAT_backend/src/routes/locationsRoutes');
const usersRoutes = require('./SAT_backend/src/routes/usersRoutes');
const questionsRoutes = require('./SAT_backend/src/routes/questionsRoutes');
const formsRoutes = require('./SAT_backend/src/routes/formsRoutes');
const auditsRoutes = require('./SAT_backend/src/routes/auditsRoutes');
const externalAuditorsRoutes = require('./SAT_backend/src/routes/externalAuditorsRoutes');
const submissionsRoutes = require('./SAT_backend/src/routes/submissionsRoutes');
const ticketsRoutes = require('./SAT_backend/src/routes/ticketsRoutes');
const dynamicFormRoutes = require('./SAT_backend/src/routes/dynamicFormRoutes');
const dashboardRoutes = require('./SAT_backend/src/routes/dashboardRoutes');
const activityLogRoutes = require('./SAT_backend/src/routes/activityLogRoutes');
const aiRoutes = require('./SAT_backend/src/routes/aiRoutes');
const auditSchedulesRoutes = require('./SAT_backend/src/routes/auditSchedulesRoutes');

// Register routes
app.use(API_PREFIX, loginRoutes);
app.use(`${API_PREFIX}/account-status`, accountStatusRoutes);
app.use(`${API_PREFIX}/roles`, rolesRoutes);
app.use(`${API_PREFIX}/departments`, departmentsRoutes);
app.use(`${API_PREFIX}/countries`, countryRoutes);
app.use(`${API_PREFIX}/audit-status`, auditStatusRoutes);
app.use(`${API_PREFIX}/tickets-status`, ticketsStatusRoutes);
app.use(`${API_PREFIX}/tickets-type`, ticketsTypeRoutes);
app.use(`${API_PREFIX}/forms-type`, formsTypeRoutes);
app.use(`${API_PREFIX}/question-type`, questionTypeRoutes);
app.use(`${API_PREFIX}/rpn`, rpnRoutes);
app.use(`${API_PREFIX}/locations`, locationsRoutes);
app.use(`${API_PREFIX}/users`, usersRoutes);
app.use(`${API_PREFIX}/questions`, questionsRoutes);
app.use(`${API_PREFIX}/forms`, formsRoutes);
app.use(`${API_PREFIX}/audits`, auditsRoutes);
app.use(`${API_PREFIX}/external-auditors`, externalAuditorsRoutes);
app.use(`${API_PREFIX}/submissions`, submissionsRoutes);
app.use(`${API_PREFIX}/tickets`, ticketsRoutes);
app.use(`${API_PREFIX}/dynamic-form`, dynamicFormRoutes);
app.use(`${API_PREFIX}/dashboard`, dashboardRoutes);
app.use(`${API_PREFIX}/activity-log`, activityLogRoutes);
app.use(`${API_PREFIX}/ai`, aiRoutes);
app.use(`${API_PREFIX}/audit-schedules`, auditSchedulesRoutes);
// Error handling middleware
const errorHandler = require('./SAT_backend/src/middlewares/errorHandler');
app.use(errorHandler);

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

app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
    const { startAuditScheduleReminderJob } = require('./services/auditScheduleReminderService');
    startAuditScheduleReminderJob();
});
