import 'dotenv/config';
import { z } from 'zod';

const required = (name: string, fallback?: string): string => {
  const value = process.env[name] ?? fallback;
  if (!value) throw new Error(`Missing required environment variable: ${name}`);
  return value;
};

const liveKitValues = {
  url: process.env.LIVEKIT_URL?.trim() || null,
  apiKey: process.env.LIVEKIT_API_KEY?.trim() || null,
  apiSecret: process.env.LIVEKIT_API_SECRET?.trim() || null,
};

const liveKitValueCount = Object.values(liveKitValues).filter(Boolean).length;
if (liveKitValueCount > 0 && liveKitValueCount < 3) {
  throw new Error('LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET must be configured together');
}

const paypalValues = {
  clientId: process.env.PAYPAL_CLIENT_ID?.trim() || null,
  clientSecret: process.env.PAYPAL_CLIENT_SECRET?.trim() || null,
};
const paypalValueCount = Object.values(paypalValues).filter(Boolean).length;
if (paypalValueCount === 1) {
  throw new Error('PAYPAL_CLIENT_ID and PAYPAL_CLIENT_SECRET must be configured together');
}

const googleValues = {
  clientId: process.env.GOOGLE_CLIENT_ID?.trim() || null,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET?.trim() || null,
};
const googleValueCount = Object.values(googleValues).filter(Boolean).length;
if (googleValueCount === 1) {
  throw new Error('GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET must be configured together');
}

const parseUrl = (name: string, fallback: string): string => {
  const value = process.env[name]?.trim() || fallback;
  try { return new URL(value).toString(); }
  catch { throw new Error(`${name} must be a valid URL`); }
};

const corsOrigins = (process.env.CORS_ORIGINS ?? '*')
  .split(',')
  .map((value) => value.trim())
  .filter(Boolean);
if (process.env.NODE_ENV === 'production' && corsOrigins.includes('*')) {
  throw new Error('CORS_ORIGINS must list explicit origins in production');
}
if (process.env.NODE_ENV === 'production' && liveKitValues.url
  && !liveKitValues.url.startsWith('wss://')) {
  throw new Error('LIVEKIT_URL must use wss:// in production');
}
if (process.env.NODE_ENV === 'production' && googleValueCount === 2) {
  const callbackUrl = parseUrl('GOOGLE_CALLBACK_URL', 'http://localhost:4000/api/auth/google/callback');
  const webReturnUrl = parseUrl('GOOGLE_WEB_RETURN_URL', 'http://localhost:3000/google-auth');
  if (!callbackUrl.startsWith('https://') || !webReturnUrl.startsWith('https://')) {
    throw new Error('GOOGLE_CALLBACK_URL and GOOGLE_WEB_RETURN_URL must use HTTPS in production');
  }
}

export const config = {
  port: Number(process.env.PORT ?? 4000),
  host: process.env.HOST ?? '0.0.0.0',
  serveWebApp: (process.env.SERVE_WEB_APP ?? 'false') === 'true',
  trustProxyHops: Math.max(0, Number(process.env.TRUST_PROXY_HOPS ?? 0) || 0),
  databaseUrl: required('DATABASE_URL'),
  jwtSecret: required('JWT_SECRET'),
  contactDataSecret: process.env.CONTACT_DATA_SECRET ?? required('JWT_SECRET'),
  jwtExpiresIn: process.env.JWT_EXPIRES_IN ?? '12h',
  corsOrigins,
  guardianQrEntryUrl: z.url().parse(
    process.env.GUARDIAN_QR_ENTRY_URL ?? 'http://localhost:3000/guardian-login',
  ),
  representativeEntryUrl: z.url().parse(
    process.env.REPRESENTATIVE_ENTRY_URL ?? 'http://localhost:3000/representative-login',
  ),
  liveKit: {
    url: liveKitValues.url ? z.url().parse(liveKitValues.url) : null,
    apiKey: liveKitValues.apiKey,
    apiSecret: liveKitValues.apiSecret,
    configured: liveKitValueCount === 3,
  },
  paypal: {
    clientId: paypalValues.clientId,
    clientSecret: paypalValues.clientSecret,
    configured: paypalValueCount === 2,
    environment: process.env.PAYPAL_ENV === 'live' ? 'live' as const : 'sandbox' as const,
    apiBase: process.env.PAYPAL_ENV === 'live'
      ? 'https://api-m.paypal.com' : 'https://api-m.sandbox.paypal.com',
  },
  google: {
    clientId: googleValues.clientId,
    clientSecret: googleValues.clientSecret,
    configured: googleValueCount === 2,
    callbackUrl: parseUrl('GOOGLE_CALLBACK_URL', 'http://localhost:4000/api/auth/google/callback'),
    appReturnUrl: parseUrl('GOOGLE_APP_RETURN_URL', 'alatalabak://google-auth'),
    webReturnUrl: parseUrl('GOOGLE_WEB_RETURN_URL', 'http://localhost:3000/google-auth'),
  },
  seedDemoAccounts: (process.env.SEED_DEMO_ACCOUNTS ?? (process.env.NODE_ENV === 'production' ? 'false' : 'true')) === 'true',
  seedUserEmail: process.env.SEED_USER_EMAIL ?? 'user@alatalabak.local',
  seedUserPassword: process.env.SEED_USER_PASSWORD ?? 'User@12345',
  seedAdminEmail: process.env.SEED_ADMIN_EMAIL ?? 'admin@alatalabak.local',
  seedAdminPassword: process.env.SEED_ADMIN_PASSWORD ?? 'Admin@12345',
  seedPartnerEmail: process.env.SEED_PARTNER_EMAIL ?? 'partner@alatalabak.local',
  seedPartnerPassword: process.env.SEED_PARTNER_PASSWORD ?? 'Partner@12345',
};
