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

export async function GET(
  request: NextRequest,
  props: { params: Promise<{ postcode: string }> }
) {
  const { postcode } = await props.params;

  if (!postcode || typeof postcode !== "string") {
    return NextResponse.json(
      { error: "Missing or invalid postcode" },
      { status: 400 }
    );
  }

  const data = await lookupPostcode(postcode);

  if (data.status === 404) {
    return NextResponse.json({ error: "Invalid postcode" }, { status: 404 });
  }

  if (data.status !== 200 || !data.result) {
    return NextResponse.json(
      { error: data.error || "Postcode lookup failed" },
      { status: data.status || 500 }
    );
  }

  return NextResponse.json({ result: data.result });
}
