const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;

function hasValue(value: string | undefined) {
  return Boolean(value && value.trim().length > 0);
}

function looksLikePlaceholder(value: string | undefined) {
  if (!value) return true;
  return (
    value.includes("your-project-ref") ||
    value.includes("your-anon-key") ||
    value.includes("your-service-role-key")
  );
}

const hasSupabasePublicEnv =
  hasValue(supabaseUrl) && hasValue(supabaseAnonKey) && !looksLikePlaceholder(supabaseUrl);

type LocalViewerRole = "admin" | "affiliate";

const localViewerRoleRaw = (process.env.LOCAL_VIEWER_ROLE ?? "admin").trim().toLowerCase();
const localViewerRole: LocalViewerRole = localViewerRoleRaw === "affiliate" ? "affiliate" : "admin";
const localViewerCountries = (process.env.LOCAL_VIEWER_COUNTRIES ?? "")
  .split(",")
  .map((country) => country.trim().toUpperCase())
  .filter(Boolean);

const disableAuthRaw = (process.env.DISABLE_AUTH ?? "").trim().toLowerCase();
const disableAuth = disableAuthRaw === "true" || disableAuthRaw === "1" || disableAuthRaw === "yes";

export const env = {
  supabaseUrl: supabaseUrl ?? "",
  supabaseAnonKey: supabaseAnonKey ?? "",
  appUrl: process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000",
  topRankingMinSent: Number(process.env.TOP_RANKING_MIN_SENT ?? "10"),
  // Security default: auth stays enabled unless explicitly disabled.
  disableAuth,
  localViewerRole,
  localViewerCountries,
  hasSupabasePublicEnv,
};
