import { existsSync } from "node:fs";
import path from "node:path";

import dotenv from "dotenv";

import { z } from "zod";

const envCandidates = [
  path.resolve(process.cwd(), ".env"),
  path.resolve(process.cwd(), "../.env"),
  path.resolve(process.cwd(), "../../.env")
];

for (const candidate of envCandidates) {
  if (existsSync(candidate)) {
    dotenv.config({ path: candidate });
    break;
  }
}

const schema = z.object({
  NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
  DATABASE_URL: z.string().min(1),
  JWT_SECRET: z.string().min(16),
  JWT_EXPIRES_IN: z.string().default("12h"),
  ADMIN_NAME: z.string().min(1).default("Rental System Admin"),
  ADMIN_EMAIL: z.string().email().default("admin@rental.local"),
  ADMIN_PASSWORD: z.string().min(6).default("Admin12345!"),
  API_PORT: z.coerce.number().int().positive().default(4000),
  APP_BASE_URL: z.string().url().default("http://localhost:3000"),
  API_BASE_URL: z.string().url().default("http://localhost:4000")
});

export const env = schema.parse(process.env);

export const isTest = env.NODE_ENV === "test";
