import { cookies } from "next/headers";
import { signValue, verifyValue } from "@/lib/session";

const COOKIE_NAME = "admin_session";
const MAX_AGE_SECONDS = 60 * 60 * 24 * 7; // 7 days

/** userId is omitted for the legacy shared-password login; set for a real AdminUser login. */
export async function createAdminSession(userId?: string) {
  const value = `admin:${userId ?? "legacy"}:${Date.now()}`;
  const token = signValue(value);
  const store = await cookies();
  store.set(COOKIE_NAME, token, {
    httpOnly: true,
    sameSite: "lax",
    secure: process.env.NODE_ENV === "production",
    path: "/",
    maxAge: MAX_AGE_SECONDS,
  });
}

export async function destroyAdminSession() {
  const store = await cookies();
  store.delete(COOKIE_NAME);
}

function parseSession(value: string): { userId: string; ts: number } | null {
  const parts = value.split(":");
  // Old sessions issued before multi-user support: "admin:<timestamp>" (2 parts).
  if (parts.length === 2 && parts[0] === "admin") {
    const ts = Number(parts[1]);
    if (!ts) return null;
    return { userId: "legacy", ts };
  }
  // Current format: "admin:<userId>:<timestamp>" (3 parts).
  if (parts.length === 3 && parts[0] === "admin") {
    const ts = Number(parts[2]);
    if (!ts) return null;
    return { userId: parts[1], ts };
  }
  return null;
}

export async function isAdminAuthed() {
  const store = await cookies();
  const token = store.get(COOKIE_NAME)?.value;
  if (!token) return false;
  const value = verifyValue(token);
  if (!value) return false;
  const parsed = parseSession(value);
  if (!parsed) return false;
  if (Date.now() - parsed.ts > MAX_AGE_SECONDS * 1000) return false;
  return true;
}

/** "legacy" for the shared-password login, or an AdminUser id for a real per-user login. */
export async function getCurrentAdminUserId(): Promise<string | null> {
  const store = await cookies();
  const token = store.get(COOKIE_NAME)?.value;
  if (!token) return null;
  const value = verifyValue(token);
  if (!value) return null;
  const parsed = parseSession(value);
  if (!parsed) return null;
  if (Date.now() - parsed.ts > MAX_AGE_SECONDS * 1000) return null;
  return parsed.userId;
}
