import { type NextRequest, NextResponse } from "next/server";
import type { ProxyFn } from "~/proxy";
import { TOKEN_CONFIG } from "~/server/auth/configs";
import { verifyToken } from "~/server/auth/jwt";

export const pswChangeProxy: ProxyFn = async (req: NextRequest) => {
	if (req.nextUrl.pathname === "/auth/aggiorna-password") {
		return;
	}

	const accessToken = req.cookies.get(
		TOKEN_CONFIG.ACCESS_TOKEN_COOKIE_NAME,
	)?.value;

	if (!accessToken) {
		return;
	}

	const { expired, session } = await verifyToken(accessToken);
	if (!session || expired) {
		return;
	}
	if (session.mustChangePassword) {
		return NextResponse.redirect(
			new URL("/auth/aggiorna-password", req.nextUrl),
		);
	}

	return;
};
