import path from 'node:path';
import dotenv from 'dotenv';
import { z } from 'zod';

dotenv.config({ path: path.resolve(__dirname, '../../.env') });

const csv = z
  .string()
  .default('')
  .transform((s) =>
    s
      .split(',')
      .map((x) => x.trim())
      .filter(Boolean),
  );
const optional = z
  .string()
  .optional()
  .transform((v) => (v ? v : undefined));

const schema = z
  .object({
    NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
    PORT: z.coerce.number().int().positive().default(3000),
    APP_URL: z.string().url().default('http://localhost:5173'),
    ADMIN_URL: z.string().url().default('http://localhost:5180'),
    CORS_ORIGINS: csv.pipe(z.array(z.string().url('CORS_ORIGINS must be comma-separated URLs'))),

    DB_HOST: z.string().default('127.0.0.1'),
    DB_PORT: z.coerce.number().int().positive().default(3306),
    DB_NAME: z.string({ error: 'DB_NAME is required' }).min(1, 'DB_NAME is required'),
    DB_USER: z.string({ error: 'DB_USER is required' }).min(1, 'DB_USER is required'),
    DB_PASSWORD: z.string().default(''),

    JWT_SECRET: z
      .string({ error: 'JWT_SECRET is required' })
      .min(32, 'JWT_SECRET must be at least 32 characters'),
    COOKIE_DOMAIN: optional,

    // Website server rendering (SEO Phase 1): folder that holds the website build (client/ + server/)
    WEBSITE_DIST: z.string().default(path.resolve(process.cwd(), '../website/dist')),
    // where rendered pages get their data: the database, or the website's sample JSON (no database yet)
    SITE_DATA: z.enum(['database', 'json']).default('database'),
    // Monitoring (SEO Phase 13), all optional: Search Console verification code, Plausible analytics
    GSC_VERIFICATION: optional,
    PLAUSIBLE_DOMAIN: optional,
    PLAUSIBLE_SRC: z.string().url().default('https://plausible.io/js/script.js'),

    // R2 + SMTP are checked again where they are used (later build steps).
    R2_ACCOUNT_ID: optional,
    R2_ACCESS_KEY_ID: optional,
    R2_SECRET_ACCESS_KEY: optional,
    R2_BUCKET: optional,
    R2_PUBLIC_URL: optional,
    SMTP_HOST: optional,
    SMTP_PORT: z.coerce.number().int().positive().default(465),
    SMTP_USER: optional,
    SMTP_PASS: optional,
    CONTACT_NOTIFY_EMAIL: optional,
  })
  .superRefine((e, ctx) => {
    if (e.NODE_ENV === 'production') {
      if (!e.DB_PASSWORD)
        ctx.addIssue({
          code: 'custom',
          path: ['DB_PASSWORD'],
          message: 'DB_PASSWORD is required in production',
        });
      if (!e.CORS_ORIGINS.length)
        ctx.addIssue({
          code: 'custom',
          path: ['CORS_ORIGINS'],
          message: 'CORS_ORIGINS is required in production',
        });
    }
  });

export type Env = z.infer<typeof schema>;

/** Test runs get safe defaults so unit tests never need a .env file. */
const testDefaults: Record<string, string> = {
  DB_NAME: 'bdmedicine_test',
  DB_USER: 'bdmedicine',
  JWT_SECRET: 'test-secret-test-secret-test-secret-123',
  CORS_ORIGINS: 'http://localhost:5173,http://localhost:5180',
};

export function loadEnv(source: NodeJS.ProcessEnv = process.env): Env {
  const input = source.NODE_ENV === 'test' ? { ...testDefaults, ...source } : source;
  const parsed = schema.safeParse(input);
  if (!parsed.success) {
    const lines = parsed.error.issues.map((i) => `  - ${i.path.join('.')}: ${i.message}`).join('\n');
    // Fail fast with a readable message (cPanel shows stderr in the app log).
    throw new Error(`Invalid environment variables:\n${lines}`);
  }
  return parsed.data;
}

export const env = loadEnv();
