import { z } from 'zod';

/**
 * Base Zod schema shared by all product backends.
 *
 * Products extend this with `.extend({...})` to add product-specific fields.
 * The base covers: server, CORS, Cosmos DB, JWT auth, DB provider.
 */
export const baseBackendConfigSchema = z.object({
  PORT: z.coerce.number().default(3000),
  HOST: z.string().default('0.0.0.0'),
  NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
  CORS_ORIGIN: z.string().optional(),
  SERVICE_NAME: z.string().default('backend'),

  DB_PROVIDER: z.enum(['cosmos', 'memory']).default('cosmos'),
  COSMOS_ENDPOINT: z.string().default(''),
  COSMOS_KEY: z.string().default(''),
  COSMOS_DATABASE: z.string().default('lysnrai'),

  JWT_SECRET: z.string().min(1, 'JWT_SECRET is required'),
  PLATFORM_JWKS_URL: z.string().url().optional(),
});

export type BaseBackendConfig = z.infer<typeof baseBackendConfigSchema>;

/**
 * Parse and validate backend config from process.env.
 *
 * @param schema — Zod object schema (typically `baseBackendConfigSchema.extend({...})`)
 * @param env — environment object (defaults to process.env)
 * @returns Validated, typed config
 */
export function parseBackendConfig<T extends z.ZodRawShape>(
  schema: z.ZodObject<T>,
  env: Record<string, string | undefined> = process.env as Record<string, string | undefined>
): z.infer<z.ZodObject<T>> {
  return schema.parse(env);
}
