import dotenv from "dotenv";
import { z } from "zod";

dotenv.config();

const envSchema = z.object({
  PORT: z.coerce.number().int().positive().default(4000),
  NODE_ENV: z
    .enum(["development", "test", "production"])
    .default("development"),
  MONGODB_URI: z.string().min(1),
  JWT_SECRET: z.string().min(20),
  JWT_EXPIRES_IN: z.string().default("7d"),
  CORS_ORIGIN: z.string().min(1).default("http://localhost:19006"),

  // Optional bootstrap admin (for first-time setup)
  ENABLE_DEFAULT_ADMIN: z
    .string()
    .optional()
    .default("false")
    .transform((val) => val === "true" || val === "1"),
  DEFAULT_ADMIN_ID: z.string().min(1).optional().default("admin"),
  DEFAULT_ADMIN_PASSWORD: z.string().min(6).optional().default("admin123"),
  DEFAULT_ADMIN_EMAIL: z
    .string()
    .email()
    .optional()
    .default("admin@somarjun.local"),
  DEFAULT_ADMIN_FULL_NAME: z
    .string()
    .min(2)
    .optional()
    .default("Somarjun Admin"),

  // SMTP (for password reset emails)
  SMTP_HOST: z.string().min(1).optional(),
  SMTP_PORT: z.coerce.number().int().positive().optional().default(587),
  SMTP_SECURE: z
    .string()
    .optional()
    .default("false")
    .transform((val) => val === "true" || val === "1"),
  SMTP_USER: z
    .string()
    .min(1)
    .optional()
    .transform((val) => (typeof val === "string" ? val.trim() : val)),
  SMTP_PASS: z
    .string()
    .min(1)
    .optional()
    .transform((val) =>
      typeof val === "string" ? val.replace(/\s+/g, "") : val
    ),
  SMTP_FROM: z.string().min(1).optional(),

  // Dev helpers
  RESET_ECHO_CODE: z
    .string()
    .optional()
    .default("false")
    .transform((val) => val === "true" || val === "1"),
});

export const env = envSchema.parse({
  PORT: process.env.PORT,
  NODE_ENV: process.env.NODE_ENV,
  MONGODB_URI: process.env.MONGODB_URI,
  JWT_SECRET: process.env.JWT_SECRET,
  JWT_EXPIRES_IN: process.env.JWT_EXPIRES_IN,
  CORS_ORIGIN: process.env.CORS_ORIGIN,

  ENABLE_DEFAULT_ADMIN: process.env.ENABLE_DEFAULT_ADMIN,
  DEFAULT_ADMIN_ID: process.env.DEFAULT_ADMIN_ID,
  DEFAULT_ADMIN_PASSWORD: process.env.DEFAULT_ADMIN_PASSWORD,
  DEFAULT_ADMIN_EMAIL: process.env.DEFAULT_ADMIN_EMAIL,
  DEFAULT_ADMIN_FULL_NAME: process.env.DEFAULT_ADMIN_FULL_NAME,

  SMTP_HOST: process.env.SMTP_HOST,
  SMTP_PORT: process.env.SMTP_PORT,
  SMTP_SECURE: process.env.SMTP_SECURE,
  SMTP_USER: process.env.SMTP_USER,
  SMTP_PASS: process.env.SMTP_PASS,
  SMTP_FROM: process.env.SMTP_FROM,

  RESET_ECHO_CODE: process.env.RESET_ECHO_CODE,
});
