import { z } from "zod";

const configSchema = z.object({
  port: z.coerce.number().min(1).max(65535).default(8000),
  logLevel: z.enum(["debug", "info", "warn", "error"]).default("info"),
  databasePath: z.string().default("./data/contracts.db"),
  paperlessBaseUrl: z.string().url().optional(),
  paperlessToken: z.string().min(1).optional(),
  paperlessExternalUrl: z.string().url().optional(),
  schedulerIntervalMinutes: z.coerce.number().min(5).default(60),
  alertDaysBefore: z.coerce.number().min(1).default(30),
  mailServer: z.string().optional(),
  mailPort: z.coerce.number().min(1).max(65535).default(587),
  mailUsername: z.string().optional(),
  mailPassword: z.string().optional(),
  mailUseTls: z.coerce.boolean().default(true),
  mailFrom: z.string().email().optional(),
  mailTo: z.string().email().optional(),
  authUsername: z.string().optional(),
  authPassword: z.string().optional(),
  authJwtSecret: z.string().optional(),
  authTokenExpiresInHours: z.coerce.number().min(1).max(168).default(12),
  ntfyServerUrl: z.string().url().optional(),
  ntfyTopic: z.string().min(1).optional(),
  ntfyToken: z.string().optional(),
  ntfyPriority: z.string().optional(),
  icalSecret: z.string().optional()
});

function parseBoolean(value: string | undefined, fallback: boolean): boolean {
  if (value === undefined) {
    return fallback;
  }
  return ["1", "true", "yes", "on"].includes(value.toLowerCase());
}

const rawConfig = {
  port: process.env.PORT,
  logLevel: process.env.LOG_LEVEL,
  databasePath: process.env.DATABASE_PATH,
  paperlessBaseUrl: process.env.PAPERLESS_BASE_URL,
  paperlessToken: process.env.PAPERLESS_TOKEN,
  paperlessExternalUrl: process.env.PAPERLESS_EXTERNAL_URL,
  schedulerIntervalMinutes: process.env.SCHEDULER_INTERVAL_MINUTES,
  alertDaysBefore: process.env.ALERT_DAYS_BEFORE,
  mailServer: process.env.MAIL_SERVER,
  mailPort: process.env.MAIL_PORT,
  mailUsername: process.env.MAIL_USERNAME,
  mailPassword: process.env.MAIL_PASSWORD,
  mailUseTls: parseBoolean(process.env.MAIL_USE_TLS, true),
  mailFrom: process.env.MAIL_FROM,
  mailTo: process.env.MAIL_TO,
  authUsername: process.env.AUTH_USERNAME,
  authPassword: process.env.AUTH_PASSWORD,
  authJwtSecret: process.env.AUTH_JWT_SECRET,
  authTokenExpiresInHours: process.env.AUTH_TOKEN_EXPIRES_IN_HOURS,
  ntfyServerUrl: process.env.NTFY_SERVER_URL,
  ntfyTopic: process.env.NTFY_TOPIC,
  ntfyToken: process.env.NTFY_TOKEN,
  ntfyPriority: process.env.NTFY_PRIORITY,
  icalSecret: process.env.ICAL_SECRET
};

export type AppConfig = z.infer<typeof configSchema>;

export const config: AppConfig = configSchema.parse(rawConfig);
