import "server-only";
import { cookies } from "next/headers";
import {
  COOKIE_NAME,
  SESSION_DURATION_MS,
  decrypt,
  encrypt,
} from "@/app/lib/session-crypto";

export async function createSession(email: string) {
  const expiresAt = new Date(Date.now() + SESSION_DURATION_MS);
  const session = await encrypt({
    userId: "admin",
    email,
    expiresAt,
  });
  const cookieStore = await cookies();
  cookieStore.set(COOKIE_NAME, session, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    expires: expiresAt,
    sameSite: "lax",
    path: "/",
  });
}

export async function deleteSession() {
  const cookieStore = await cookies();
  cookieStore.delete(COOKIE_NAME);
}

export async function getSession() {
  const cookieStore = await cookies();
  const cookie = cookieStore.get(COOKIE_NAME)?.value;
  return decrypt(cookie);
}

export { COOKIE_NAME, decrypt };
