const DEV_API_URL_FALLBACK = "http://localhost:8000/api/admin";

function resolveApiUrl(): string {
  const value = process.env.NEXT_PUBLIC_API_URL;
  if (value && value.length > 0) return value;

  if (process.env.NODE_ENV === "production") {
    throw new Error(
      "NEXT_PUBLIC_API_URL is not set. Define it in the environment before building for production.",
    );
  }

  if (typeof window !== "undefined") {
    // Warn once in the browser during dev so the fallback isn't silent.
    console.warn(
      `[env] NEXT_PUBLIC_API_URL not set, falling back to ${DEV_API_URL_FALLBACK}`,
    );
  }
  return DEV_API_URL_FALLBACK;
}

const apiUrl = resolveApiUrl();

export const env = {
  apiUrl,
  // Backend origin (strips the "/api/admin" suffix), used for storage URLs.
  backendOrigin: apiUrl.replace(/\/api\/admin\/?$/, ""),
  appName: process.env.NEXT_PUBLIC_APP_NAME || "Dadycar Admin",
  // Real-time (Laravel Echo over Pusher/Reverb). Without a key the support inbox falls back to polling.
  pusher: {
    key: process.env.NEXT_PUBLIC_PUSHER_APP_KEY || "",
    host: process.env.NEXT_PUBLIC_PUSHER_HOST || "",
    port: Number(process.env.NEXT_PUBLIC_PUSHER_PORT || 443),
    scheme: process.env.NEXT_PUBLIC_PUSHER_SCHEME || "https",
    cluster: process.env.NEXT_PUBLIC_PUSHER_APP_CLUSTER || "mt1",
    authUrl: process.env.NEXT_PUBLIC_BROADCAST_AUTH_URL || `${apiUrl.replace(/\/api\/admin\/?$/, "")}/broadcasting/auth`,
  },
  isProduction: process.env.NODE_ENV === "production",
  isDevelopment: process.env.NODE_ENV === "development",
} as const;
