import cors from 'cors';

/** Vite dev: localhost vs 127.0.0.1, and ports 3000–3010 when 3000/3001 are already taken. */
function getDevViteOrigins(): string[] {
  const out: string[] = [];
  for (let port = 3000; port <= 3010; port++) {
    out.push(`http://localhost:${port}`, `http://127.0.0.1:${port}`);
  }
  return out;
}

// Configure allowed origins - uses only FRONTEND_URL from environment
const getAllowedOrigins = (): string[] | boolean => {
  const frontendUrl = process.env.FRONTEND_URL;
  const isProduction = process.env.NODE_ENV === 'production';

  // In development, if FRONTEND_URL is not set, default to localhost:3000
  if (!frontendUrl) {
    if (isProduction) {
      console.error('❌ ERROR: FRONTEND_URL environment variable is not set!');
      console.error('   CORS will block all origins. This will prevent frontend connections.');
      console.error('   To fix: Set FRONTEND_URL environment variable with your frontend URL(s)');
      console.error('   Example: FRONTEND_URL=https://your-frontend-domain.com');
      console.error('   Multiple origins: FRONTEND_URL=https://app1.com,https://app2.com');
      return [];
    } else {
      console.warn('⚠️  WARNING: FRONTEND_URL not set. Defaulting Vite dev origins (localhost + 127.0.0.1).');
      console.warn('   Set FRONTEND_URL in .env if you use another host/port.');
      return getDevViteOrigins();
    }
  }

  // If FRONTEND_URL is set to '*', allow all origins
  if (frontendUrl === '*') {
    if (isProduction) {
      console.warn('⚠️  WARNING: FRONTEND_URL is set to allow ALL origins (*) in production. This is not recommended for security.');
    }
    return true; // This allows any origin
  }

  // Parse comma-separated URLs or use single URL
  let origins = frontendUrl.split(',').map(url => url.trim()).filter(Boolean);

  if (origins.length === 0) {
    console.error('❌ ERROR: FRONTEND_URL is set but contains no valid URLs!');
    return isProduction ? [] : getDevViteOrigins(); // Fallback for development
  }

  // In development allow common Vite host/port combos (avoids CORS when Vite bumps to 3002+)
  if (!isProduction) {
    for (const o of getDevViteOrigins()) {
      if (!origins.includes(o)) origins.push(o);
    }
  }

  console.log(`✅ CORS: Allowing origins from FRONTEND_URL: ${origins.join(', ')}`);
  return origins;
};

export const corsMiddleware = cors({
  origin: getAllowedOrigins(),
  credentials: true, // Allow cookies and authorization headers
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept'],
  exposedHeaders: ['X-Total-Count', 'X-Page-Count'],
  optionsSuccessStatus: 200,
});