import type { CorsOptions } from 'cors';

// All AeThex domains
const allowedOrigins = [
  // Production domains
  'https://aethex.app',
  'https://aethex.co',
  'https://aethex.network',
  'https://aethex.net',
  'https://aethex.tech',
  'https://aethex.id',
  'https://aethex.cloud',
  'https://kernel.aethex.cloud',
  'https://api.aethex.cloud',
  'https://cdn.aethex.cloud',
  'https://aethex.education',
  'https://aethex.studio',
  'https://aethex.shop',
  'https://aethex.support',
  'https://aethex.dev',
  'https://aethex.info',
  'https://aethex.blog',
  'https://aethex.locker',
  'https://aethex.bot',
  'https://aethex.live',
  'https://aethex.fun',
  'https://aethex.space',
  'https://aethex.bio',
  'https://aethex.me',
  'https://aethex.biz',
  'https://aethex.pro',
  'https://aethex.foundation',
  'https://aethex.us',
  'https://aethex.sbs',
  'https://aethex.online',
  'https://aethex.site',
  // Development
  'http://localhost:5173',
  'http://localhost:5000',
  'http://localhost:3000',
  'http://127.0.0.1:5173',
  'http://127.0.0.1:5000',
  'http://127.0.0.1:3000',
];

export function getCorsOptions(): CorsOptions {
  return {
    origin: (origin, callback) => {
      // Allow requests with no origin (mobile apps, Postman, curl, etc.)
      if (!origin) {
        return callback(null, true);
      }

      // Check if origin is in allowed list
      if (allowedOrigins.includes(origin)) {
        callback(null, true);
      } else {
        console.warn(`CORS blocked origin: ${origin}`);
        callback(new Error(`Origin ${origin} not allowed by CORS`));
      }
    },
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowedHeaders: [
      'Content-Type',
      'Authorization',
      'X-Requested-With',
      'Accept',
      'Origin',
    ],
    exposedHeaders: ['Set-Cookie'],
    maxAge: 86400, // 24 hours
  };
}
