import { z } from 'zod';

// Environment variables
const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
  PORT: z.string().transform(Number).default(3000),
  HOST: z.string().default('0.0.0.0'),
  API_RATE_LIMIT_WINDOW: z.string().transform(Number).default(60000), // 1 minute
  API_RATE_LIMIT_MAX_REQUESTS: z.string().transform(Number).default(100),
  CORS_ORIGIN: z.string().default('http://localhost:5173'),
  ALLOWED_ORIGINS: z.string().default(''),
});

export const apiEnv = envSchema.parse({
  NODE_ENV: process.env.NODE_ENV,
  PORT: process.env.PORT,
  HOST: process.env.HOST,
  API_RATE_LIMIT_WINDOW: process.env.API_RATE_LIMIT_WINDOW,
  API_RATE_LIMIT_MAX_REQUESTS: process.env.API_RATE_LIMIT_MAX_REQUESTS,
  CORS_ORIGIN: process.env.CORS_ORIGIN,
  ALLOWED_ORIGINS: process.env.ALLOWED_ORIGINS,
});

/**
 * Parse ALLOWED_ORIGINS into a validated set.
 * In production, rejects wildcards ('*') and empty values.
 * In development, falls back to localhost.
 */
export function getCorsOrigins(): string | string[] {
  const origins = (apiEnv.ALLOWED_ORIGINS || '').split(',').map(s => s.trim()).filter(Boolean);

  if (apiEnv.NODE_ENV === 'production') {
    if (origins.length === 0) {
      throw new Error(
        'CORS origin validation (FRE-4749): ALLOWED_ORIGINS is empty in production. ' +
        'Set ALLOWED_ORIGINS to a comma-separated list of allowed origins.'
      );
    }
    for (const origin of origins) {
      if (origin === '*') {
        throw new Error(
          'CORS origin validation (FRE-4749): wildcard (*) ALLOWED_ORIGIN in production.'
        );
      }
      let isValidProtocol = true;
      try {
        const url = new URL(origin);
        if (url.protocol !== 'https:' && url.protocol !== 'http:') {
          isValidProtocol = false;
          throw new Error(
            `CORS origin validation (FRE-4749): invalid protocol "${url.protocol}" in "${origin}". Expected http: or https:`
          );
        }
      } catch (err) {
        if (err instanceof Error && !isValidProtocol) throw err;
        throw new Error(
          `CORS origin validation (FRE-4749): malformed origin "${origin}": ${err instanceof Error ? err.message : String(err)}`
        );
      }
    }
    return origins;
  }

  return apiEnv.CORS_ORIGIN || 'http://localhost:5173';
}

// Rate limit configuration by tier
export const rateLimitConfig = {
  basic: {
    windowMs: 60000, // 1 minute
    maxRequests: 100,
  },
  plus: {
    windowMs: 60000,
    maxRequests: 500,
  },
  premium: {
    windowMs: 60000,
    maxRequests: 2000,
  },
};

// API versioning configuration
export const apiVersioning = {
  defaultVersion: '1',
  headerName: 'X-API-Version',
  queryParam: 'api-version',
};

// Logging configuration
export const loggingConfig = {
  level: apiEnv.NODE_ENV === 'production' ? 'info' : 'debug',
  transport: apiEnv.NODE_ENV === 'development' ? {
    target: 'pino-pretty',
    options: {
      colorize: true,
      translateTime: true,
    },
  } : undefined,
};
