export const SESSION_COOKIE = "dashboard_session";
const HMAC_PAYLOAD = "autobuilder-dashboard-authenticated";

export function getPassword(): string | undefined {
  return process.env.DASHBOARD_PASSWORD;
}

export function isAuthEnabled(): boolean {
  return !!getPassword();
}

async function hmacSha256(key: string, message: string): Promise<string> {
  const enc = new TextEncoder();
  const cryptoKey = await crypto.subtle.importKey(
    "raw",
    enc.encode(key),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["sign"],
  );
  const sig = await crypto.subtle.sign("HMAC", cryptoKey, enc.encode(message));
  return Array.from(new Uint8Array(sig))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
}

export async function createSessionToken(password: string): Promise<string> {
  return hmacSha256(password, HMAC_PAYLOAD);
}

export async function verifySessionToken(token: string): Promise<boolean> {
  const password = getPassword();
  if (!password) return true;
  const expected = await createSessionToken(password);
  if (token.length !== expected.length) return false;
  let mismatch = 0;
  for (let i = 0; i < expected.length; i++) {
    mismatch |= token.charCodeAt(i) ^ expected.charCodeAt(i);
  }
  return mismatch === 0;
}
