import "server-only";
import { z } from "zod";

/**
 * Server-side env, validated at first import. Never exposed to the client.
 * Fail fast: a misconfigured deploy throws here instead of silently 500-ing.
 */
const schema = z.object({
  LIBRE_DESK_API_URL: z.string().url(),
  LIBRE_DESK_API_KEY: z.string().min(1),
  LIBRE_DESK_API_SECRET: z.string().min(1),
  LIBREDESK_INBOX_ID: z.coerce.number().int().positive(),
  // Optional: assign new conversations to a team (your "Support" team id).
  LIBREDESK_SUPPORT_TEAM_ID: z.coerce.number().int().positive().optional(),
  // Optional: enables Turnstile verification when present.
  TURNSTILE_SECRET_KEY: z.string().min(1).optional(),
});

const parsed = schema.safeParse(process.env);
if (!parsed.success) {
  throw new Error(
    `Invalid Libredesk intake env:\n${parsed.error.issues
      .map((i) => `  - ${i.path.join(".")}: ${i.message}`)
      .join("\n")}`,
  );
}

export const env = parsed.data;
