import crypto from "crypto";
import { cookies } from "next/headers";

const COOKIE_NAME = "rakku_maintenance_bypass";

// Cookie speichert nicht das Passwort selbst, sondern einen HMAC damit —
// ändert sich das hinterlegte Passwort später, werden alte Bypass-Cookies
// automatisch ungültig, ohne dass irgendwo eine Liste gültiger Tokens
// gepflegt werden müsste.
function computeToken(password: string): string {
  const secret = process.env.SESSION_SECRET || "";
  return crypto.createHmac("sha256", secret).update(password).digest("hex");
}

export async function setMaintenanceBypassCookie(password: string) {
  const store = await cookies();
  store.set(COOKIE_NAME, computeToken(password), {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 30,
  });
}

export async function hasMaintenanceBypass(configuredPassword: string): Promise<boolean> {
  if (!configuredPassword) return false;
  const store = await cookies();
  const cookieValue = store.get(COOKIE_NAME)?.value;
  if (!cookieValue) return false;
  return cookieValue === computeToken(configuredPassword);
}
