if (process.env.NODE_ENV !== 'development') {
    console.log = function () { };
    console.error = function () { };
    console.warn = function () { };
}

const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const db = require('./config/db.config');
// const Auth = require('./controllers/Auth')
const session = require('express-session');
const SequelizeStore = require('connect-session-sequelize')(session.Store);
require('dotenv').config()
const routes = require('./routes/routes');
// const requestHandler = require('./middleware/processRequest');
const path = require('path');

const sessionStore = new SequelizeStore({
    db: db,
    tableName: 'node_ses',
});

const app = express();
app.use(cors());
// const allowedOrigins = [
//     'https://dummy.logiclane.tech',
//     // 'https://bend.logiclane.tech',
//     // 'https://swback.logiclane.tech',
//     // 'http://localhost',
//     // 'http://localhost:3000',
// ];

// const corsOptions = {
//     origin: function (origin, callback) {
//         console.log('CORS Origin:', origin || 'Undefined (Same-Origin or Direct Request)');

//         if (!origin || allowedOrigins.includes(origin)) {
//             callback(null, true);
//         } else {
//             callback(new Error('Not allowed by CORS'));
//         }
//     },
//     credentials: true, // Enable cookies & sessions
// };

// // Apply global middleware but exclude specific routes
// app.use((req, res, next) => {
//     let origin = req.headers.origin || req.headers.referer || `${req.protocol}://${req.get('host')}`;
//     console.log('Detected Origin:', origin);

//     if (!req.headers.origin) {
//         req.headers.origin = origin;
//     }
//     next();
// });

// // Exclude specific routes from CORS
// const excludedRoutes = [
//     '/api/email',
//     '/api/sms',
//     '/api/emailLogWebhook',
//     '/api/forumpay/webhook',
//     '/api/forumpay/requestPayment',
//     '/api/forumpay/requestPaymentBit',
//     '/api/gametime/webhook',
//     '/api/gametimesend',
//     '/api/gametime',
//     '/api/crypto',
//     '/api/crypto/webhook',
//     '/api/nmi2',
//     '/api/nmi/webhook',
//     '/api/nmi/webhook2',
//     '/api/idenfy/webhook',
//     '/api/crons/paymentcrons',
//     '/api/crons/nmiwebhookcron',
//     '/api/as/process-payment',
//     '/api/as/3ds-notify',
//     /^\/api\/as\/check-status\/[^/]+\/[^/]+$/
// ];

// // Apply CORS conditionally
// app.use((req, res, next) => {
//     const isExcluded = excludedRoutes.some(route =>
//         typeof route === 'string' ? route === req.path : route.test(req.path)
//     );

//     if (isExcluded) {
//         return next(); // Skip CORS for these routes
//     }
//     cors(corsOptions)(req, res, next); // Apply CORS for other routes
// });

// app.use((err, req, res, next) => {
//     if (err.message === 'Not allowed by CORS') {
//         return res.status(403).json({ error: 'CORS Error: Origin not allowed' });
//     }
//     next(err);
// });
app.use(helmet({
    contentSecurityPolicy: {
        directives: {
            defaultSrc: ["'self'"],
            scriptSrc: ["'self'", "'unsafe-inline'", "'unsafe-eval'"],
            styleSrc: ["'self'", "'unsafe-inline'"],
            frameAncestors: ["*"], // ✅ Allow all iframe embedding
        },
    },
}));

app.use(
    session({
        secret: "test11235@", // Change this to a strong secret
        store: sessionStore,
        resave: false,
        saveUninitialized: false, // Prevent empty sessions
        cookie: { secure: false }, // Set to `true` if using HTTPS
    })
);

// Sync the session table
sessionStore.sync();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// app.use(requestHandler);

app.set('trust proxy', 1);
app.use('/public', express.static(path.join(__dirname, 'public'), {
    setHeaders: (res, filePath) => {
        if (filePath.endsWith('.avif')) {
            res.setHeader('Content-Type', 'image/avif');
            res.setHeader('Content-Disposition', 'attachment; filename="' + path.basename(filePath) + '"');
        }
    }
}));
app.use('/public/evidence', express.static(path.join(__dirname, 'public/evidence'), {
    setHeaders: (res, filePath) => {
        if (filePath.endsWith('.avif')) {
            res.setHeader('Content-Type', 'image/avif');
            res.setHeader('Content-Disposition', 'attachment; filename="' + path.basename(filePath) + '"');
        }
    }
}));

// Define a simple route
app.get('/', (req, res) => {
    res.send('Hello World!');
});
app.use('/api', routes);
// Start the server
const PORT = process.env.PORT || 80;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
