import { NextResponse } from "next/server";
import { userTokenStatus } from "./token.check";

export async function forbiddenRoute(request) {
  const home = new URL("/", request.url);
  const response = NextResponse.next();
  const homePage = NextResponse.redirect(home);

  const searchParams = request.nextUrl.searchParams;
  const searchParamsEntries = Object.fromEntries(searchParams.entries());
  const cookies = Object.fromEntries(
    request.cookies.getAll().map((c) => Object.values(c))
  );

  if (searchParamsEntries.redirect) {
    const destination = new URL(searchParamsEntries.redirect, request.url);
    const destonationPage = NextResponse.redirect(destination);

    destonationPage.cookies.delete("reason");

    const status = await userTokenStatus(request);
    if (status) return destonationPage;
  }

  if (!cookies?.reason) return homePage;

  response.cookies.delete("reason");
  return response;
}
