import cors from 'cors';

// 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 {
      // Dev fallback: allow localhost:3000
      console.warn('⚠️  WARNING: FRONTEND_URL not set. Defaulting to http://localhost:3000 for development.');
      console.warn('   To avoid this warning, set FRONTEND_URL=http://localhost:3000 in your .env file');
      return ['http://localhost:3000'];
    }
  }

  // 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 ? [] : ['http://localhost:3000']; // Fallback for development
  }

  // In development always allow localhost:3000 (Vite default) so frontend works even if FRONTEND_URL is 3001
  if (!isProduction && !origins.includes('http://localhost:3000')) {
    origins = ['http://localhost:3000', ...origins];
  }

  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,
});