import { encode } from "next-auth/jwt";
import type { NextResponse } from "next/server";
import type { UserRole } from "@/types";

export const DEFAULT_MAX_AGE_SEC = 60 * 60 * 24 * 7; // 7 days
export const IMPERSONATION_MAX_AGE_SEC = 60 * 60 * 4; // 4 hours

export function sessionCookieName(secure: boolean): string {
  return secure
    ? "__Secure-next-auth.session-token"
    : "next-auth.session-token";
}

export async function encodeSessionJwt(payload: {
  id: string;
  role: UserRole;
  workspaceId: string | null;
  name: string;
  email: string;
  picture?: string | null;
  impersonatorAdminId?: string;
}, maxAgeSec = DEFAULT_MAX_AGE_SEC): Promise<string> {
  const secret = process.env.NEXTAUTH_SECRET;
  if (!secret) {
    throw new Error("NEXTAUTH_SECRET is not configured");
  }

  return encode({
    token: {
      ...payload,
      sub: payload.id,
      lastChecked: Date.now(),
    },
    secret,
    maxAge: maxAgeSec,
  });
}

export function applySessionCookie(
  res: NextResponse,
  jwt: string,
  secure: boolean,
  maxAgeSec = DEFAULT_MAX_AGE_SEC
) {
  const name = sessionCookieName(secure);
  const other = sessionCookieName(!secure);

  res.cookies.set(other, "", {
    httpOnly: true,
    path: "/",
    maxAge: 0,
    expires: new Date(0),
    sameSite: "lax",
    secure: !secure,
  });

  res.cookies.set(name, jwt, {
    httpOnly: true,
    path: "/",
    maxAge: maxAgeSec,
    sameSite: "lax",
    secure,
  });
}
