import type { FastifyReply, FastifyRequest } from "fastify";
import { env } from "../env.js";

export type SessionPayload = {
  userId: string;
  lawFirmId: string | null;
  lawFirmSlug: string | null;
  email: string;
  roleCodes: string[];
  displayName: string;
};

const maxAgeSeconds = 60 * 60 * 24 * 7;

export function setSessionCookie(reply: FastifyReply, payload: SessionPayload) {
  const token = reply.server.jwt.sign(payload, {
    expiresIn: `${maxAgeSeconds}s`,
  });

  reply.setCookie(env.COOKIE_NAME, token, {
    path: "/",
    httpOnly: true,
    sameSite: "lax",
    secure: env.COOKIE_SECURE,
    maxAge: maxAgeSeconds,
  });
}

export function clearSessionCookie(reply: FastifyReply) {
  reply.clearCookie(env.COOKIE_NAME, {
    path: "/",
    httpOnly: true,
    sameSite: "lax",
    secure: env.COOKIE_SECURE,
  });
}

export async function requireSession(
  request: FastifyRequest,
  reply: FastifyReply,
) {
  try {
    return await request.jwtVerify<SessionPayload>();
  } catch {
    throw reply.unauthorized("Authentication required");
  }
}
