import dotenv from 'dotenv';

dotenv.config();

function required(name: string): string {
  const value = process.env[name];

  if (!value) {
    throw new Error(`Variable d'environnement manquante: ${name}`);
  }

  return value;
}

function numberFromEnv(name: string, defaultValue: number): number {
  const value = process.env[name];

  if (!value) {
    return defaultValue;
  }

  const parsed = Number(value);

  if (Number.isNaN(parsed)) {
    throw new Error(`Variable d'environnement invalide: ${name}`);
  }

  return parsed;
}

export const env = {
  port: numberFromEnv('PORT', 3000),
  nodeEnv: process.env.NODE_ENV || 'development',
  frontendUrl: required('FRONTEND_URL'),
  databaseUrl: required('DATABASE_URL'),
  db: {
    server: required('DB_SERVER'),
    port: numberFromEnv('DB_PORT', 1433),
    name: required('DB_NAME'),
    user: required('DB_USER'),
    password: required('DB_PASSWORD'),
  },
  azure: {
    tenantId: required('AZURE_TENANT_ID'),
    clientId: required('AZURE_CLIENT_ID'),
  },
};
