import { NextRequest, NextResponse } from "next/server";

function unauthorized(message = "Authentification requise.") {
  return new NextResponse(message, {
    status: 401,
    headers: {
      "WWW-Authenticate": 'Basic realm="Espace Agent administratif ENRGETIC", charset="UTF-8"',
      "Cache-Control": "no-store",
    },
  });
}

export function proxy(request: NextRequest) {
  const expectedUser = process.env.PORTAL_ADMIN_USERNAME?.trim();
  const expectedPassword = process.env.PORTAL_ADMIN_PASSWORD;

  if (!expectedUser || !expectedPassword) {
    return new NextResponse("Accès administratif non configuré.", {
      status: 503,
      headers: { "Cache-Control": "no-store" },
    });
  }

  const authorization = request.headers.get("authorization");
  if (!authorization?.startsWith("Basic ")) return unauthorized();

  try {
    const decoded = atob(authorization.slice(6));
    const separator = decoded.indexOf(":");
    if (separator < 0) return unauthorized();

    const username = decoded.slice(0, separator);
    const password = decoded.slice(separator + 1);
    if (username !== expectedUser || password !== expectedPassword) {
      return unauthorized("Identifiants incorrects.");
    }
  } catch {
    return unauthorized();
  }

  return NextResponse.next();
}

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