import "server-only";

import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { getSessionSecret, SESSION_COOKIE_NAME, SESSION_TTL_SECONDS } from "@/lib/auth/constants";
import { createSessionTokenValue, type SessionPayload, verifySessionTokenValue } from "@/lib/auth/session-token";

export type { SessionPayload } from "@/lib/auth/session-token";

export function createSessionToken(userId: string, email: string) {
  return createSessionTokenValue(userId, email, getSessionSecret(), SESSION_TTL_SECONDS);
}

export function verifySessionToken(token: string | undefined): SessionPayload | null {
  return verifySessionTokenValue(token, getSessionSecret());
}

export function setSessionCookie(response: NextResponse, token: string) {
  response.cookies.set({
    name: SESSION_COOKIE_NAME,
    value: token,
    httpOnly: true,
    sameSite: "lax",
    secure: process.env.NODE_ENV === "production",
    maxAge: SESSION_TTL_SECONDS,
    path: "/",
  });
}

export function clearSessionCookie(response: NextResponse) {
  response.cookies.set({
    name: SESSION_COOKIE_NAME,
    value: "",
    httpOnly: true,
    sameSite: "lax",
    secure: process.env.NODE_ENV === "production",
    maxAge: 0,
    path: "/",
  });
}

export async function getSessionPayload() {
  const cookieStore = await cookies();
  const token = cookieStore.get(SESSION_COOKIE_NAME)?.value;

  return verifySessionToken(token);
}
