"use server";
import { cookies } from "next/headers";
import { sealData, unsealData } from "iron-session";
import { SESSION_SECRET } from "@/constants";

export async function setSession(data: any) {
  const password = SESSION_SECRET!;
  const sealed = await sealData(data, { password });

  const cookie = await cookies();

  cookie.set("session", JSON.stringify(data), {
    httpOnly: true,
    path: "/",
    //maxAge: 60 * 60 * 24, // 1 day
    maxAge: 30 * 24 * 60 * 60, // 30 day
  });
  // cookie.set("session", sealed, {
  //     httpOnly: true,
  //     secure: true,
  //     sameSite: "lax",
  //     path: "/",
  //     maxAge: 30 * 24 * 60 * 60,
  // });
}

export async function getSession() {
  const password = SESSION_SECRET!;
  const ck = await cookies();
  const cookie = ck.get("session")?.value;
  if (!cookie) return null;

  try {
    const data = await cookie;
    return data;
  } catch {
    return null; // tampered or invalid
  }
}

export async function destroySession() {
  const cookieStore = await cookies(); // ✅ await
  cookieStore.delete("session");
}
