import { type NextRequest, NextResponse } from "next/server";
import type { ProxyFn } from "~/proxy";

const UPDATE_COODKIE_NAME = "app_version";

export const updaterProxy: ProxyFn = async (req: NextRequest) => {
	const url = req.nextUrl.clone();

	const updateToken = req.cookies.get(UPDATE_COODKIE_NAME)?.value;
	if (!process.env.NEXT_PUBLIC_TEST) {
		return;
	}

	if (!updateToken) {
		// First time visitor or cookie not set, set the cookie
		const res = NextResponse.rewrite(url);
		res.cookies.set(UPDATE_COODKIE_NAME, process.env.NEXT_PUBLIC_TEST, {
			maxAge: 60 * 60 * 24 * 30, // 30 days
			path: "/",
		});
		return res;
	}
	if (updateToken !== process.env.NEXT_PUBLIC_TEST) {
		// Version has changed, perform a hard refresh and update the cookie
		const res = NextResponse.rewrite(url);
		res.cookies.set(UPDATE_COODKIE_NAME, process.env.NEXT_PUBLIC_TEST, {
			maxAge: 60 * 60 * 24 * 30, // 30 days
			path: "/",
		});
		return res;
	}

	return;
};
