import "dotenv/config";
import { z } from "zod";

const schema = z.object({
  NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
  PORT: z.coerce.number().int().default(4100),
  HOST: z.string().default("127.0.0.1"),
  DATABASE_URL: z.string().startsWith("mysql://"),
  STORAGE_DIR: z.string().default("./storage"),
  APP_URL: z.string().url().default("http://localhost:8080"),
  APP_ENCRYPTION_KEY: z.string().regex(/^[0-9a-f]{64}$/, "64 hex characters"),
  MAIL_DELIVERY: z.enum(["on", "off"]).default("off"),
  /** Sign in with one click as each role. Only for testing: the server refuses to start with it in production. */
  DEMO_LOGIN: z.enum(["on", "off"]).default("off"),
  BACKUP_DATABASE_URL: z.string().startsWith("mysql://").optional(),
  BACKUP_DIR: z.string().optional(),
  BACKUP_COPY_DIR: z.string().optional(),
  BACKUP_HOUR: z.coerce.number().int().min(0).max(23).default(1),
  MYSQL_BIN_DIR: z.string().default(""),
  ARCHIVE_DB: z.string().regex(/^\w{1,64}$/).optional(),
  DEVELOPER_NAME: z.string().optional(),
  DEVELOPER_URL: z.string().url().optional(),
  DEVELOPER_EMAIL: z.string().email().optional(),
  TRUST_PROXY: z.enum(["true", "false"]).default("false"),
  /** On while V1 is the live system and V2 is rebuilt from it every night: V2 can be read but not changed, because a rebuild would erase the change. */
  MIRROR_MODE: z.enum(["on", "off"]).default("off"),
}).refine((e) => !(e.NODE_ENV === "production" && e.DEMO_LOGIN === "on"), "DEMO_LOGIN must be off in production.")
  .refine((e) => e.NODE_ENV !== "production" || e.APP_URL.startsWith("https://"), "APP_URL must use https in production: cookies are only sent over https.");
export const env = schema.parse(process.env);
