import {z} from 'zod'

const EnvSchema = z
  .object({
    DATABASE_URL: z.url(),
    REDIS_URL: z.url(),
    RESEND_API_KEY: z.string().default(''),
    EMAIL_FROM: z.string().default(''),
    APP_SCHEME: z.string().default('crumbs'),
    PUBLIC_API_URL: z.url(),
    LOCATIONIQ_API_KEY: z.string().min(1),
    LOCATIONIQ_BASE_URL: z
      .url()
      .default('https://us1.locationiq.com/v1'),
    PORT: z.coerce.number().default(4000),
    TRUST_PROXY: z.stringbool().default(false),
    // routes/dev.ts deliberately re-reads the live process.env instead
    DEV_ROUTES: z.stringbool().default(false),
    NODE_ENV: z
      .enum(['development', 'production', 'test'])
      .default('development'),
    // disk serves uploads locally; r2 uses cloudflare object storage
    STORAGE_DRIVER: z.enum(['disk', 'r2']).default('disk'),
    UPLOADS_DIR: z.string().default('./uploads'),
    R2_ENDPOINT: z.url().optional(),
    R2_ACCESS_KEY_ID: z.string().optional(),
    R2_SECRET_ACCESS_KEY: z.string().optional(),
    R2_BUCKET: z.string().optional(),
    R2_PUBLIC_BASE_URL: z.url().optional(),
  })
  .superRefine((val, ctx) => {
    if (val.STORAGE_DRIVER !== 'r2') return
    const required = [
      'R2_ENDPOINT',
      'R2_ACCESS_KEY_ID',
      'R2_SECRET_ACCESS_KEY',
      'R2_BUCKET',
      'R2_PUBLIC_BASE_URL',
    ] as const
    for (const key of required)
      if (!val[key])
        ctx.addIssue({
          code: 'custom',
          path: [key],
          message: `${key} is required when STORAGE_DRIVER=r2`,
        })
  })

export const env = EnvSchema.parse(process.env)
