import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import {
  adminUnauthorizedResponse,
  attachAdminHeaders,
  isAdminRequestAuthorized,
  stripClientAdminHeaders,
} from "@/lib/admin-auth";

export function middleware(request: NextRequest) {
  const url = request.nextUrl;
  const isAdminPath = url.pathname.startsWith("/admin");
  const strippedHeaders = stripClientAdminHeaders(request);

  if (isAdminPath) {
    if (!isAdminRequestAuthorized(request)) {
      return adminUnauthorizedResponse();
    }

    const headers = attachAdminHeaders(request);
    return NextResponse.next({
      request: {
        headers,
      },
    });
  }

  // Check if there is a referral parameter ?ref=
  const ref = url.searchParams.get('ref');

  if (ref) {
    const response = NextResponse.redirect(url.pathname);
    // Set cookie for 30 days
    response.cookies.set('vw_referral_agent', ref, {
      maxAge: 30 * 24 * 60 * 60,
      path: '/',
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
    });
    return response;
  }
  
  return NextResponse.next({
    request: {
      headers: strippedHeaders,
    },
  });
}

export const config = {
  matcher: [
    '/((?!_next/static|_next/image|favicon.ico).*)',
  ],
};
