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

const COOKIE_NAME = "customer_session";
const MAX_AGE_SECONDS = 60 * 60 * 24 * 30; // 30 days

export async function createCustomerSession(customerId: string) {
  const value = `${customerId}:${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 destroyCustomerSession() {
  const store = await cookies();
  store.delete(COOKIE_NAME);
}

export async function getCurrentCustomerId(): 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 lastColon = value.lastIndexOf(":");
  if (lastColon === -1) return null;
  const customerId = value.slice(0, lastColon);
  const ts = Number(value.slice(lastColon + 1));
  if (!ts || Date.now() - ts > MAX_AGE_SECONDS * 1000) return null;
  return customerId;
}
