import { z } from "zod";

/**
 * Build-time validated environment.
 *
 * NEXT_PUBLIC_* values are inlined by Turbopack via the literal `process.env`
 * reads below, so they resolve in client bundles too. Defaults mirror
 * production so local dev and CI work without an `.env` file; override per
 * environment (Vercel project settings) when a value differs.
 */
const schema = z.object({
  /** Marketing site root. */
  NEXT_PUBLIC_SITE_URL: z.url().default("https://seoinsight.app"),
  /** Dashboard app root — auth (login/signup) and the product live here. */
  NEXT_PUBLIC_APP_URL: z.url().default("https://dashboard.seoinsight.app"),
  /**
   * OpenPanel analytics. Both are public per OpenPanel's docs (the clientId is
   * meant to live in the browser), so they're inlined client-side. Events go
   * straight to the self-hosted instance (`apiUrl`); CORS on the instance
   * allows our origins. The recorder script is served first-party from
   * `/public/op1.js` (adblock-safe), so no proxy route is involved. Optional:
   * when unset, analytics doesn't mount. Must be present at BUILD time —
   * `NEXT_PUBLIC_*` values are inlined into the bundle, not read at runtime.
   */
  NEXT_PUBLIC_OP_CLIENT_ID: z.string().min(1).optional(),
  /** Self-hosted OpenPanel API base URL, e.g. `https://analytics.example.com/api`. */
  NEXT_PUBLIC_OP_API_URL: z.url().optional(),
  /**
   * Google Analytics 4 Measurement ID (format `G-XXXXXXX`). Public, inlined
   * client-side via `@next/third-parties`. Optional: GA only mounts when set,
   * so swapping properties is just an env change + redeploy.
   */
  NEXT_PUBLIC_GA4_MEASUREMENT_ID: z
    .string()
    .regex(/^G-[A-Z0-9]+$/, "must look like G-XXXXXXX")
    .optional(),
});

const parsed = schema.safeParse({
  NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,
  NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,
  NEXT_PUBLIC_OP_CLIENT_ID: process.env.NEXT_PUBLIC_OP_CLIENT_ID,
  NEXT_PUBLIC_OP_API_URL: process.env.NEXT_PUBLIC_OP_API_URL,
  NEXT_PUBLIC_GA4_MEASUREMENT_ID: process.env.NEXT_PUBLIC_GA4_MEASUREMENT_ID,
});

if (!parsed.success) {
  console.error(
    "❌ Invalid environment variables:",
    z.flattenError(parsed.error).fieldErrors,
  );
  throw new Error("Invalid environment variables");
}

const env = parsed.data;

/** Marketing site root, e.g. `https://seoinsight.app`. */
export const siteUrl = env.NEXT_PUBLIC_SITE_URL;
/** Dashboard app root (auth lives here), e.g. `https://dashboard.seoinsight.app`. */
const appUrl = env.NEXT_PUBLIC_APP_URL;
/** External auth entry points on the dashboard app. */
export const loginUrl = `${appUrl}/login`;
export const signupUrl = `${appUrl}/signup`;

/** OpenPanel client id (undefined when analytics is not configured). */
export const opClientId = env.NEXT_PUBLIC_OP_CLIENT_ID;
/** Self-hosted OpenPanel API base URL events are sent to directly. */
export const opApiUrl = env.NEXT_PUBLIC_OP_API_URL;
/** Google Analytics 4 Measurement ID (undefined when GA is not configured). */
export const ga4MeasurementId = env.NEXT_PUBLIC_GA4_MEASUREMENT_ID;
