import { z } from 'zod';

const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
  PORT: z.string().default('3000'),
  DATABASE_URL: z.string().default('postgresql://postgres:postgres@localhost:5432/qrmaster?schema=public'),
  NEXTAUTH_URL: z.string().default('http://localhost:3050'),
  NEXTAUTH_SECRET: z.string().default('development-secret-change-in-production'),
  GOOGLE_CLIENT_ID: z.string().optional(),
  GOOGLE_CLIENT_SECRET: z.string().optional(),
  REDIS_URL: z.string().optional(),
  IP_SALT: z.string().default('development-salt-change-in-production'),
  ENABLE_DEMO: z.string().default('false'),

  // Cloudflare R2 (S3 Compatible)
  R2_ACCOUNT_ID: z.string().optional(),
  R2_ACCESS_KEY_ID: z.string().optional(),
  R2_SECRET_ACCESS_KEY: z.string().optional(),
  R2_BUCKET_NAME: z.string().default('qrmaster-menus'),
  R2_PUBLIC_URL: z.string().optional(),
  MAX_UPLOAD_SIZE: z.string().default('10485760'), // 10MB default
});

// During build, we might not have all env vars, so we'll use defaults
const isBuildTime = process.env.NEXT_PHASE === 'phase-production-build' || !process.env.DATABASE_URL;

export const env = isBuildTime
  ? envSchema.parse({
    ...process.env,
    DATABASE_URL: process.env.DATABASE_URL || 'postgresql://postgres:postgres@db:5432/qrmaster?schema=public',
    NEXTAUTH_URL: process.env.NEXTAUTH_URL || 'http://localhost:3050',
    NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET || 'development-secret-change-in-production',
    IP_SALT: process.env.IP_SALT || 'development-salt-change-in-production',
  })
  : envSchema.parse(process.env);