import { z } from 'zod';

export const McpdConfigSchema = z.object({
  port: z.number().int().positive().default(3000),
  host: z.string().default('0.0.0.0'),
  databaseUrl: z.string().min(1),
  logLevel: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace']).default('info'),
  corsOrigins: z.array(z.string()).default(['*']),
  rateLimitMax: z.number().int().positive().default(100),
  rateLimitWindowMs: z.number().int().positive().default(60_000),
});

export type McpdConfig = z.infer<typeof McpdConfigSchema>;

export function loadConfigFromEnv(env: Record<string, string | undefined> = process.env): McpdConfig {
  return McpdConfigSchema.parse({
    port: env['MCPD_PORT'] !== undefined ? parseInt(env['MCPD_PORT'], 10) : undefined,
    host: env['MCPD_HOST'],
    databaseUrl: env['DATABASE_URL'],
    logLevel: env['MCPD_LOG_LEVEL'],
    corsOrigins: env['MCPD_CORS_ORIGINS']?.split(',').map((s) => s.trim()),
    rateLimitMax: env['MCPD_RATE_LIMIT_MAX'] !== undefined ? parseInt(env['MCPD_RATE_LIMIT_MAX'], 10) : undefined,
    rateLimitWindowMs: env['MCPD_RATE_LIMIT_WINDOW_MS'] !== undefined ? parseInt(env['MCPD_RATE_LIMIT_WINDOW_MS'], 10) : undefined,
  });
}
