import { z } from 'zod';

const schema = z.object({
  PORT: z.coerce.number().int().positive().default(3201),
  QUINN_MACSYNC_DB_URL: z.string().min(10),
  SERVICE_TOKEN: z.string().min(16),
  SSO_VALIDATE_URL: z.string().url().default('http://localhost:3025/auth/validate'),
  NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
  STORAGE_BACKEND: z.enum(['local', 's3']).default('local'),
  STORAGE_LOCAL_PATH: z.string().default('./data/blobs'),
  // S3-compatible object store (MinIO / DO Spaces / AWS / R2). Always signed.
  S3_ENDPOINT: z.string().url().optional(),
  S3_ACCESS_KEY: z.string().optional(),
  S3_SECRET_KEY: z.string().optional(),
  S3_BUCKET: z.string().default('mac-sync'),
  S3_REGION: z.string().default('us-east-1'),
  S3_FORCE_PATH_STYLE: z.coerce.boolean().default(false),
  S3_PRESIGN_TTL_SECONDS: z.coerce.number().int().positive().default(900),
  /** Embedding inference endpoint. Required from env — no LAN default (fail fast). */
  MODEL_BOSS_EMBED_URL: z.string().url(),
  /** Redis for BullMQ queues/workers. Defaults to a local instance on the host. */
  REDIS_URL: z.string().url().default('redis://127.0.0.1:6379'),
});

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

export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
  const parsed = schema.safeParse(env);
  if (!parsed.success) {
    const issues = parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ');
    throw new Error(`invalid config: ${issues}`);
  }
  return parsed.data;
}
