const cors = require('cors');
const { one } = require('../db');

function isLocalDevOrigin(origin) {
  try {
    const url = new URL(origin);
    return ['localhost', '127.0.0.1'].includes(url.hostname);
  } catch {
    return false;
  }
}

function createCorsMiddleware() {
  const persistedCors = one('SELECT value FROM app_settings WHERE key = ?', ['cors_allowed_domains'])?.value || '';
  const allowedOrigins = (process.env.DEPRECORE_CORS_ORIGINS || persistedCors || 'http://localhost:5173,http://127.0.0.1:5173')
    .split(',')
    .map((origin) => origin.trim())
    .filter(Boolean);

  return cors({
    origin(origin, callback) {
      if (!origin || allowedOrigins.includes(origin) || isLocalDevOrigin(origin)) return callback(null, true);
      return callback(new Error('Origin is not allowed by DepreCore CORS settings'));
    },
    credentials: true
  });
}

module.exports = {
  createCorsMiddleware
};
