export const AUTH_TENANT_STORAGE_KEY = "athena_auth_tenant_id";
export const AUTH_TENANT_HEADER_STORAGE_KEY = "athena_auth_tenant_header";
export const AUTH_TENANT_COOKIE_NAME = "athena_auth_tenant";
export const AUTH_TENANT_HEADER_COOKIE_NAME = "athena_auth_tenant_header";
export const DEFAULT_AUTH_TENANT_HEADER = "x-athena-tenant";

export type TenantSelection = {
  tenantId: string;
  headerName: string;
};

function normalizeHeaderName(input: string): string {
  const trimmed = input.trim().toLowerCase();
  if (!trimmed) return DEFAULT_AUTH_TENANT_HEADER;
  if (/^[a-z0-9-]+$/.test(trimmed)) return trimmed;
  return DEFAULT_AUTH_TENANT_HEADER;
}

export function normalizeTenantSelection(input: Partial<TenantSelection>): TenantSelection {
  return {
    tenantId: (input.tenantId ?? "").trim(),
    headerName: normalizeHeaderName(input.headerName ?? DEFAULT_AUTH_TENANT_HEADER),
  };
}

export function readTenantSelectionFromStorage(): TenantSelection {
  if (typeof window === "undefined") {
    return { tenantId: "", headerName: DEFAULT_AUTH_TENANT_HEADER };
  }

  const tenantId = window.localStorage.getItem(AUTH_TENANT_STORAGE_KEY) ?? "";
  const headerName =
    window.localStorage.getItem(AUTH_TENANT_HEADER_STORAGE_KEY) ??
    DEFAULT_AUTH_TENANT_HEADER;
  return normalizeTenantSelection({ tenantId, headerName });
}

function setCookie(name: string, value: string, maxAgeSeconds: number) {
  if (typeof document === "undefined") return;
  const encodedValue = encodeURIComponent(value);
  document.cookie = `${name}=${encodedValue}; Path=/; Max-Age=${maxAgeSeconds}; SameSite=Lax`;
}

export function writeTenantSelectionToStorage(input: Partial<TenantSelection>) {
  if (typeof window === "undefined") return;
  const normalized = normalizeTenantSelection(input);
  window.localStorage.setItem(AUTH_TENANT_STORAGE_KEY, normalized.tenantId);
  window.localStorage.setItem(
    AUTH_TENANT_HEADER_STORAGE_KEY,
    normalized.headerName,
  );

  // Keep cookies in sync so the Next.js proxy can inject tenant headers upstream.
  if (normalized.tenantId) {
    setCookie(AUTH_TENANT_COOKIE_NAME, normalized.tenantId, 60 * 60 * 24 * 30);
    setCookie(
      AUTH_TENANT_HEADER_COOKIE_NAME,
      normalized.headerName,
      60 * 60 * 24 * 30,
    );
  } else {
    setCookie(AUTH_TENANT_COOKIE_NAME, "", 0);
    setCookie(AUTH_TENANT_HEADER_COOKIE_NAME, "", 0);
  }
}

export function getTenantHeaderRecord(
  input?: Partial<TenantSelection>,
): Record<string, string> {
  const selection = input ? normalizeTenantSelection(input) : readTenantSelectionFromStorage();
  if (!selection.tenantId) return {};
  return { [selection.headerName]: selection.tenantId };
}
