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

dotenv.config({ path: join(__dirname, "../../.env") });

const schema = z.object({
  NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
  DATABASE_URL: z.string().min(1),
  PORT: z.coerce.number().int().positive().default(5000),
  SESSION_SECRET: z.string().min(16),
  PP_BASE_URL: z.string().min(1),
  ENCRYPTION_KEY: z.string().length(64, "ENCRYPTION_KEY must be 64 hex chars (32 bytes AES-256)"),
  LOG_LEVEL: z.string().default("info"),
});

const result = schema.safeParse(process.env);

if (!result.success) {
  const formatted = result.error.issues
    .map((i) => `  ${i.path.join(".")}: ${i.message}`)
    .join("\n");
  throw new Error(`Invalid environment variables:\n${formatted}`);
}

export const env = result.data;
