import "server-only";
import { cookies } from "next/headers";
import { getIronSession, IronSession } from "iron-session";
import { getCookieSecret } from "./client";

export interface SessionData {
  did?: string;
}

const SESSION_OPTIONS = {
  cookieName: "sidetrail-session",
  password: "",
  cookieOptions: {
    secure: process.env.NODE_ENV === "production",
    httpOnly: true,
    sameSite: "lax" as const,
    path: "/",
  },
};

export async function getSession(): Promise<IronSession<SessionData>> {
  const cookieStore = await cookies();
  return getIronSession<SessionData>(cookieStore, {
    ...SESSION_OPTIONS,
    password: getCookieSecret(),
  });
}

export async function getCurrentDid(): Promise<string | null> {
  const session = await getSession();
  return session.did || null;
}
