import {
  ADMIN_TOKEN_COOKIE_MAX_AGE_SECONDS,
  ADMIN_TOKEN_STORAGE_KEY,
} from "@/lib/admin-token-constants";

const COOKIE_BASE_OPTIONS = {
  httpOnly: true,
  sameSite: "lax",
  path: "/",
  maxAge: ADMIN_TOKEN_COOKIE_MAX_AGE_SECONDS,
} as const;

export function readAdminTokenFromCookieString(
  cookieHeader: string | null | undefined,
): string | null {
  if (!cookieHeader) {
    return null;
  }

  const prefix = `${ADMIN_TOKEN_STORAGE_KEY}=`;
  for (const part of cookieHeader.split(";")) {
    const trimmed = part.trim();
    if (!trimmed.startsWith(prefix)) {
      continue;
    }
    const raw = trimmed.slice(prefix.length);
    if (!raw) {
      return null;
    }
    try {
      const decoded = decodeURIComponent(raw).trim();
      return decoded !== "" ? decoded : null;
    } catch {
      return null;
    }
  }

  return null;
}

export function readAdminTokenFromDocumentCookie(): string | null {
  return null;
}

export function writeAdminTokenCookie(token: string | null): void {
  void token;
}

export function adminTokenCookieOptions(secure: boolean) {
  return {
    ...COOKIE_BASE_OPTIONS,
    secure,
  };
}

export function expiredAdminTokenCookieOptions(secure: boolean) {
  return {
    ...COOKIE_BASE_OPTIONS,
    secure,
    maxAge: 0,
  };
}
