/* =====================================================================
   lib/customer-auth.js — Sitzungs-Logik für echte Kundenkonten (Google-/PayPal-Login).
   Bewusst GETRENNT von lib/auth.js (Zugangscode-Schranke) — eigenes Geheimnis, eigenes Cookie,
   1:1 Prinzip wie im Original (functions/_shared/customer-auth.js). Einziger Unterschied:
   getCustomer() fragt jetzt synchron better-sqlite3 statt async D1 ab.
   ===================================================================== */

import { db } from "../db.js";

export const CUSTOMER_COOKIE_NAME = "vandiy_customer_session";
export const CUSTOMER_SESSION_TAGE = 30;

function b64urlEncode(bytes) {
  let bin = "";
  bytes.forEach((b) => (bin += String.fromCharCode(b)));
  return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function b64urlDecodeToBytes(str) {
  str = str.replace(/-/g, "+").replace(/_/g, "/");
  while (str.length % 4) str += "=";
  const bin = atob(str);
  return Uint8Array.from(bin, (c) => c.charCodeAt(0));
}
async function hmacKey(secret) {
  return crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
}

export async function signCustomerSession(customerId, secret) {
  const payload = JSON.stringify({ cid: customerId, exp: Date.now() + CUSTOMER_SESSION_TAGE * 24 * 60 * 60 * 1000 });
  const payloadB64 = b64urlEncode(new TextEncoder().encode(payload));
  const key = await hmacKey(secret);
  const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payloadB64));
  return `${payloadB64}.${b64urlEncode(new Uint8Array(sig))}`;
}

export async function verifyCustomerSession(token, secret) {
  if (!token || !token.includes(".")) return null;
  const [payloadB64, sigB64] = token.split(".");
  try {
    const key = await hmacKey(secret);
    const valid = await crypto.subtle.verify("HMAC", key, b64urlDecodeToBytes(sigB64), new TextEncoder().encode(payloadB64));
    if (!valid) return null;
    const payload = JSON.parse(new TextDecoder().decode(b64urlDecodeToBytes(payloadB64)));
    if (!payload.exp || payload.exp < Date.now()) return null;
    return payload; // { cid, exp }
  } catch {
    return null;
  }
}

/** Liefert den eingeloggten customers-Datensatz für die aktuelle Anfrage, oder null. Kunden-ID
 *  kommt NIE direkt vom Client, immer nur aus der signierten, serverseitig geprüften Sitzung. */
export async function getCustomer(req) {
  if (!process.env.CUSTOMER_SESSION_SECRET) return null;
  const token = req.cookies?.[CUSTOMER_COOKIE_NAME];
  const payload = token ? await verifyCustomerSession(token, process.env.CUSTOMER_SESSION_SECRET) : null;
  if (!payload?.cid) return null;
  const row = db.prepare(`SELECT id, email, name, provider, created_at FROM customers WHERE id = ?`).get(payload.cid);
  return row || null;
}

export function setCustomerCookie(res, token, maxAgeSekunden) {
  res.cookie(CUSTOMER_COOKIE_NAME, token, {
    path: "/",
    maxAge: maxAgeSekunden * 1000,
    httpOnly: true,
    secure: true,
    sameSite: "lax",
  });
}

export function clearCustomerCookie(res) {
  res.clearCookie(CUSTOMER_COOKIE_NAME, { path: "/" });
}
