import { NextRequest, NextResponse } from "next/server";
import { API_URL } from "./lib/constants";
import getMe from "./lib/getMe";

export async function middleware(request: NextRequest) {
	const sessionCookie = request.cookies.get("auth_token")?.value;
	// console.log(sessionCookie);
	if (!sessionCookie) {
		return NextResponse.redirect(
			new URL(
				`/login?redirectTo=${encodeURIComponent(request.url)}`,
				request.url,
			),
		);
	}

	try {
		console.log(API_URL);
		const js = await getMe(sessionCookie);
		if (js?.status === "Error") {
			console.log(js.message);
			return NextResponse.redirect(
				new URL(
					`/login?redirectTo=${encodeURIComponent(request.url)}`,
					request.url,
				),
			);
		}
	} catch (e: any) {
		console.log(e);
		return NextResponse.redirect(
			new URL(
				`/login?redirectTo=${encodeURIComponent(request.url)}`,
				request.url,
			),
		);
	}

	return NextResponse.next();
}

export const config = {
	matcher: ["/dashboard/:path*"],
};
