/**
 * CORS / Socket.IO — อนุญาตเฉพาะ origin ที่ระบุ (จาก env + รายการ dev)
 * ตั้ง CORS_ORIGINS คั่นด้วย comma เช่น http://localhost:5173,http://127.0.0.1:5174
 */
function normalizeOrigin(origin: string): string {
  const o = origin.trim().replace(/\/+$/, '').toLowerCase();
  return o;
}

export function buildAllowedOrigins(): string[] {
  const raw = process.env.CORS_ORIGINS || process.env.CORS_ORIGIN || '';
  const fromEnv = raw
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean);

  const devDefaults =
    process.env.NODE_ENV === 'production'
      ? []
      : [
          'http://localhost:5173',
          'http://127.0.0.1:5173',
          'http://localhost:5174',
          'http://127.0.0.1:5174',
          'http://localhost:5175',
          'http://127.0.0.1:5175',
          'http://localhost:3000',
          'http://127.0.0.1:3000',
          'http://localhost:4173',
          'http://127.0.0.1:4173',
        ];

  return [...new Set([...devDefaults, ...fromEnv])];
}

export function isOriginAllowed(origin: string | undefined): boolean {
  if (!origin) {
    return true;
  }
  const n = normalizeOrigin(origin);
  const allowed = buildAllowedOrigins().map(normalizeOrigin);
  return allowed.includes(n);
}
