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

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

export async function signToken(
	payload: Session,
	expiresIn: string,
	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);
		const parse = sessionSchema.safeParse(payload.payload);
		if (!parse.success) {
			//console.error("JWT payload invalid:", parse.error);
			return null;
		}
		return parse.data;
	} catch (e) {
		console.error("JWT verification Internal Error:", (e as Error).message);
		return null;
	}
}
