import { NextRequest, NextResponse } from "next/server";
import {
  COOKIE_NAME,
  SESSION_DURATION_MS,
  decrypt,
  encrypt,
} from "@/app/lib/session-crypto";

export default async function proxy(req: NextRequest) {
  const path = req.nextUrl.pathname;
  const isAdminRoute = path.startsWith("/admin");
  const isLoginRoute = path === "/admin/login";

  if (!isAdminRoute) {
    return NextResponse.next();
  }

  const cookie = req.cookies.get(COOKIE_NAME)?.value;
  const session = await decrypt(cookie);
  const isAuthenticated = Boolean(session?.userId);

  if (!isLoginRoute && !isAuthenticated) {
    return NextResponse.redirect(new URL("/admin/login", req.nextUrl));
  }

  if (isLoginRoute && isAuthenticated) {
    return NextResponse.redirect(new URL("/admin", req.nextUrl));
  }

  if (session?.userId) {
    const expiresAt = new Date(Date.now() + SESSION_DURATION_MS);
    const refreshedSession = await encrypt({
      userId: String(session.userId),
      email: String(session.email ?? ""),
      expiresAt,
    });
    const response = NextResponse.next();
    response.cookies.set(COOKIE_NAME, refreshedSession, {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      expires: expiresAt,
      sameSite: "lax",
      path: "/",
    });
    return response;
  }

  return NextResponse.next();
}

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