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

const envSchema = z.object({
  NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
  DATABASE_URL: z.string().min(1),
  PORT: z.coerce.number().default(4000),
  CLIENT_URL: z.string().default("http://localhost:5173"),
  API_URL: z.string().default("http://localhost:4000"),
  JWT_SECRET: z.string().min(1),
  JWT_EXPIRES_IN: z.string().default("7d"),
  SMTP_HOST: z.string().optional(),
  SMTP_PORT: z.coerce.number().optional(),
  SMTP_USER: z.string().optional(),
  SMTP_PASS: z.string().optional(),
  EMAIL_FROM: z.string().default("My Assisto <notifications@myassisto.local>"),
  UPLOAD_DIR: z.string().default("uploads"),
  SYSTEM_ADMIN_EMAILS: z.string().default(""),
  TOKEN_ENCRYPTION_KEY: z.string().default("change-me-in-production-32-chars"),
});

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

// Placeholder secrets are fine for local dev (and match backend/.env.example),
// but must never reach production — fail startup loudly rather than silently
// running with a known, public key.
if (env.NODE_ENV === "production") {
  const insecureDefaults: Record<string, string> = {
    TOKEN_ENCRYPTION_KEY: "change-me-in-production-32-chars",
    JWT_SECRET: "change-me-in-production",
  };
  for (const [key, placeholder] of Object.entries(insecureDefaults)) {
    if (env[key as keyof typeof env] === placeholder) {
      throw new Error(`Refusing to start in production with a placeholder ${key}. Set a real secret in the environment.`);
    }
  }
}

export const systemAdminEmails = new Set(
  env.SYSTEM_ADMIN_EMAILS.split(",").map((e) => e.trim().toLowerCase()).filter(Boolean)
);
