import dotenv from "dotenv";
import { asBoolean, asNumber, required } from "./config-helpers";

// Carga de variables de entorno (.env). Si ya están en el entorno, no se sobreescriben.
dotenv.config();

type NodeEnv = "development" | "test" | "production";
type DbSyncMode = "none" | "alter" | "force";
type DbDialect = "postgres" | "mysql" | "mariadb" | "mssql" | "sqlite";

const NODE_ENV = (process.env.NODE_ENV as NodeEnv) ?? "development";
const isProd = NODE_ENV === "production";
const isDev = NODE_ENV === "development";

const HOST = process.env.HOST ?? "0.0.0.0";
const PORT = asNumber(process.env.PORT, 3002);

// En producción exigimos FRONTEND_URL definido (según requisitos actuales).
const FRONTEND_URL = isProd
  ? required("FRONTEND_URL", process.env.FRONTEND_URL)
  : (process.env.FRONTEND_URL ?? "http://localhost:5173");

// Base de datos (dos modos: URL o parámetros sueltos)
const DATABASE_URL = process.env.DATABASE_URL; // p.ej. postgres://user:pass@host:5432/dbname

const DB_DIALECT = (process.env.DB_DIALECT as DbDialect | undefined) ?? undefined;
const DB_HOST = process.env.DB_HOST ?? "localhost";
const DB_PORT = asNumber(process.env.DB_PORT, 5432);
const DB_NAME = process.env.DB_NAME ?? "";
const DB_USER = process.env.DB_USER ?? "";
const DB_PASSWORD = process.env.DB_PASSWORD ?? "";

const DB_LOGGING = asBoolean(process.env.DB_LOGGING, false);

// Modo de sincronización usado por model-loader.ts
const DB_SYNC_MODE =
  (process.env.DB_SYNC_MODE as DbSyncMode | undefined) ?? (isProd ? "none" : "alter");

// Opcional: timezone para Sequelize (según necesidades)
const APP_TIMEZONE = process.env.APP_TIMEZONE ?? "Europe/Madrid";

// Proxy (no usáis ahora, pero dejamos la variable por si se activa en el futuro)
const TRUST_PROXY = asNumber(process.env.TRUST_PROXY, 0);

export const ENV = {
  NODE_ENV,
  HOST,
  PORT,
  FRONTEND_URL,
  DATABASE_URL,
  DB_DIALECT,
  DB_HOST,
  DB_PORT,
  DB_NAME,
  DB_USER,
  DB_PASSWORD,
  DB_LOGGING,
  DB_SYNC_MODE,
  APP_TIMEZONE,
  TRUST_PROXY,
} as const;

export const Flags = {
  isProd,
  isDev,
  isTest: NODE_ENV === "test",
} as const;
