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

export async function GET(request: NextRequest) {
  const postcode = request.nextUrl.searchParams.get("postcode");

  // Check if the postcode is provided
  if (!postcode) {
    return new NextResponse("Postcode parameter is missing", { status: 400 });
  }

  const headers = {
    Accept: "application/json",
    Authorization: `Basic ${process.env.EPC_AUTH_TOKEN ?? ""}`,
  };

  try {
    const url = `https://epc.opendatacommunities.org/api/v1/domestic/search?postcode=${postcode}&size=1000`;

    const headers = {
      Accept: "application/json",
      Authorization: `Basic ${process.env.EPC_AUTH_TOKEN ?? ""}`,
    };

    const response = await fetch(url, {
      headers: headers,
      next: { revalidate: 120 },
    });
    const data = await response.json();

    // Handle the response from the external API and return it
    return NextResponse.json(data);
  } catch (error) {
    console.error("Error fetching data:", error);
    return NextResponse.json({ message: "Internal server error", status: 500 });
  }
}
