import 'dotenv/config';
import express from 'express';
import { setupCronJobs } from './routes/cronJobs.js';

import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import rateLimit from "express-rate-limit";
import bodyParser from 'body-parser';
import websiteRoute from "./routes/website.route.js";
import settingProfileRoutes from "./routes/settingProfile.js";
import userInfo from "./routes/userInfo.js"
import authRoutes from "./routes/authRoutes.js";
//import voteRoutes from "./routes/vote.routes.js";
import voteRoutes from "./routes/vote.routes.js"
import submitAiWebsite from './routes/submitAiWebsite.js';  //  route for AiWebsite
import submitDirectory from './routes/submitDirectory.js'; //  route for Directory submissions
import dashboard from './routes/dashboard.js'; //  route for Directory submissions
import postJoB from './routes/postJob.js'; //  route for Directory submissions
import coupon from './routes/couponRoute.js';
import Favorite from "./routes/favorites.js"
import paymentRoutes from './routes/paymentRoutes.js'; // Payment verification routes
import awards from "./routes/awards.js"
import search from "./routes/search.js"
import deleteRoutes from "./routes/deleteRoutes.js";
import contactRoute from './routes/contactRoute.js'; // Contact form route
const app = express();
import db from './config/db.js';

// middlewares
app.use(helmet({
  crossOriginResourcePolicy: { policy: "cross-origin" }
}));

// CORS configuration - MUST BE BEFORE body parser
const corsOptions = {
  origin: function(origin, callback) {
    // Allow requests with no origin (like mobile apps or curl requests)
    if (!origin) return callback(null, true);

    const allowedOrigins = [
      'http://localhost:3000',
      'http://localhost:5173',
      'http://cssawwwards.com',
      'https://cssawwwards.com',
      'http://www.cssawwwards.com',
      'https://www.cssawwwards.com'
    ];

    // Check for subdomain patterns
    const subdomainPattern = /^https?:\/\/[a-zA-Z0-9-]+\.cssawwwards\.com$/;
    const isSubdomain = subdomainPattern.test(origin);

    if (allowedOrigins.includes(origin) || isSubdomain) {
      // Return the specific origin that made the request
      callback(null, origin);
    } else {
      console.log('❌ CORS blocked origin:', origin);
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Cache-Control', 'Pragma', 'Expires', 'Vary', 'Accept'],
  exposedHeaders: ['Cache-Control', 'Pragma', 'Expires', 'Vary'],
  optionsSuccessStatus: 200,
  preflightContinue: false,
  maxAge: 86400 // 24 hours
};

app.use(cors(corsOptions));

// Body parser - AFTER CORS
app.use(bodyParser.json({ limit: '100mb' }));
app.use(bodyParser.urlencoded({ limit: '100mb', extended: true }));

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

app.use(morgan('dev'));


const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 min
  max: 20, // 5 attempts per IP
  standardHeaders: true,
  legacyHeaders: false,
  message: {
    error: "Too many attempts. Please try again later."
  }
});

// 🔒 GLOBAL NO-CACHE MIDDLEWARE - Prevents all caching across entire application
app.use((req, res, next) => {
  res.set({
    'Cache-Control': 'no-store, no-cache, must-revalidate, private, max-age=0',
    'Pragma': 'no-cache',
    'Expires': '0',
    'Vary': 'Authorization, Accept-Encoding'
  });
  next();
});

// db connection
db();

// Routes here
app.use("/api/submissions", websiteRoute);  // For handling website submissions
app.use("/api/profiles", settingProfileRoutes);  // For setting profiles
app.use("/api/userInfo", userInfo)
app.use("/api/auth",authLimiter, authRoutes);  // For user authentication
app.use("/api/votes", voteRoutes);  // For handling votes
app.use("/api/awards", awards);
app.use("/api/ai-websites", submitAiWebsite);  // New route for AiWebsite submissions
app.use("/api/submit-directory", submitDirectory);  // api route for Directory submissions
app.use("/api/search", search);
app.use("/api/postJoB", postJoB);  //  api route for JobPost submissions
app.use("/api/dashboard", dashboard);  // api route for user Dashboard
app.use("/api/coupons", coupon);  // Coupon validation routes
app.use("/api/favorite", Favorite);
app.use("/api/delete", deleteRoutes);
app.use("/api/payments", paymentRoutes);  // Payment verification routes
app.use("/api/contact", contactRoute);  // Contact form route

// Global error handling
app.use((err, req, res, next) => {
  console.error("🔥 Global error:", err);
  res.status(500).json({ message: "Something broke in middleware", err });
});
// Initialize cron jobs when server starts
setupCronJobs();
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`✅ server running at http://localhost:${PORT}`);
});
