import { SignJWT, jwtVerify } from "jose";
import { env } from "~/env.mjs";
import { TRPCError } from "@trpc/server";
import { sessionSchema, type Session } from "~/server/api/trpc";

export const ACCESS_TOKEN_COOKIE_NAME = "access_token";
export const REFRESH_TOKEN_COOKIE_NAME = "refresh_token";

const secret = new TextEncoder().encode(env.JWT_SECRET);

export async function signToken(
  payload: Session,
  expiresIn = "1h",
  type: "accessToken" | "refreshToken",
) {
  try {
    return await new SignJWT({ payload, type })
      .setProtectedHeader({ alg: "HS256" })
      .setIssuedAt()
      .setExpirationTime(expiresIn)
      .sign(secret);
  } catch (e) {
    throw new TRPCError({
      code: "INTERNAL_SERVER_ERROR",
      message: "Error signing JWT token: " + (e as Error).message,
    });
  }
}

export async function verifyToken(token: string): Promise<Session | null> {
  try {
    const { payload } = await jwtVerify(token, secret);
    return sessionSchema.parse(payload.payload);
  } catch (e) {
    console.error("JWT verification error:", (e as Error).message);
    return null;
  }
}
