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

dotenv.config();

const stringWithDefault = (fallback: string) =>
  z.preprocess((value) => {
    if (typeof value !== "string") return value;
    const trimmed = value.trim();
    return trimmed.length === 0 ? undefined : trimmed;
  }, z.string().default(fallback));

const trimmedString = () =>
  z.preprocess((value) => {
    if (typeof value !== "string") return value;
    return value.trim();
  }, z.string());

const buildCorsOrigins = (rawCorsOrigin: string) =>
  Array.from(
    new Set(
      rawCorsOrigin
        .split(",")
        .map((origin) => origin.trim())
        .filter(Boolean)
    )
  );

const envSchema = z.object({
  PORT: z.coerce.number().default(4050),
  CHAT_DATABASE_URL: trimmedString().pipe(z.string().min(1)),
  JWT_SECRET: trimmedString().pipe(z.string().min(8)),
  CORS_ORIGIN: stringWithDefault("https://antigol.ru,http://localhost:3000"),
  CHAT_MESSAGE_MAX_LENGTH: z.coerce.number().default(4000)
});

export const env = envSchema.parse(process.env);
export const corsOrigins = buildCorsOrigins(env.CORS_ORIGIN);
