import { cookies } from "next/headers";
import { createHash, timingSafeEqual } from "crypto";

const COOKIE_NAME = "piff_admin_session";
const COOKIE_MAX_AGE = 60 * 60 * 8; // 8 hours

function expectedToken(): string {
  const pw = process.env.ADMIN_PASSWORD ?? "";
  // Token = sha256(password + ":piff-admin")
  return createHash("sha256").update(`${pw}:piff-admin`).digest("hex");
}

/** Constant-time comparison of submitted password vs ADMIN_PASSWORD. */
export function verifyPassword(submitted: string): boolean {
  const a = Buffer.from(submitted ?? "", "utf8");
  const b = Buffer.from(process.env.ADMIN_PASSWORD ?? "", "utf8");
  if (a.length === 0 || b.length === 0) return false;
  if (a.length !== b.length) {
    // still do a comparison to avoid early-exit timing
    timingSafeEqual(Buffer.alloc(8), Buffer.alloc(8));
    return false;
  }
  return timingSafeEqual(a, b);
}

export function setAdminCookie() {
  cookies().set(COOKIE_NAME, expectedToken(), {
    httpOnly: true,
    sameSite: "lax",
    secure: process.env.NODE_ENV === "production",
    maxAge: COOKIE_MAX_AGE,
    path: "/",
  });
}

export function clearAdminCookie() {
  cookies().set(COOKIE_NAME, "", { maxAge: 0, path: "/" });
}

/** True if the request carries a valid admin session cookie. */
export function isAdmin(): boolean {
  const c = cookies().get(COOKIE_NAME)?.value ?? "";
  if (!c) return false;
  const a = Buffer.from(c, "utf8");
  const b = Buffer.from(expectedToken(), "utf8");
  if (a.length !== b.length) return false;
  return timingSafeEqual(a, b);
}
