import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
export async function handleAuth(
    request: NextRequest,
    response: NextResponse
) {

    const { pathname } = request.nextUrl;

    const restrictedPaths = [
        "/customer/login",
        "/customer/register"
    ];


    const isRestricted =  restrictedPaths.some(path => pathname.startsWith(path));

    if (!isRestricted) {
        return response;
    }

    const token = await getToken({
        req: request,
        secret: process.env.NEXTAUTH_SECRET
    });

    if (!token) {
        return response;
    }


    /**
     * 创建 redirect response
     */
    const redirectResponse = NextResponse.redirect(new URL("/",request.url));

    /**
     * 复制之前 response 的 cookies
     *
     * 保留 currency cookie
     */
    response.cookies.getAll().forEach(cookie => {
        redirectResponse.cookies.set(cookie);
    });



    return redirectResponse;

}