const { logger } = require('nodejs-log-agent');
const { cors_origin } = require('../models'); // atau path model kamu
const cors = require('cors');

const dynamicCors = async (req, callback) => {
  try {
    const origins = await cors_origin.findAll({
      where: { is_active: true },
      attributes: ['origin'],
    });

    const allowedOrigins = origins.map(row => row.origin);

    const corsOptions = {
      origin: function (origin, callback) {
        // allow requests with no origin (like mobile apps or curl)
        if (!origin) return callback(null, true);
        if (allowedOrigins.includes(origin)) {
          callback(null, true);
        } else {
          callback(new Error('Not allowed by CORS'));
          logger.error(`[CORS] Origin ${origin} not allowed by CORS policy.`);
        }
      },
      optionsSuccessStatus: 200,
    };

    callback(null, corsOptions);
  } catch (error) {
    callback(error, null);
    logger.error(`[CORS] Error setting up CORS policy: ${error.message}`, {
      message: error.message,
      stack: error.stack,
      context: 'Error setting up CORS policy.',
    });
  }
};

module.exports = cors(dynamicCors);
