import { NextRequest, NextResponse } from "next/server";
import { lookupPincode } from "@/lib/locations";

export async function GET(
  _req: NextRequest,
  ctx: { params: Promise<{ pin: string }> },
) {
  try {
    const { pin } = await ctx.params;
    const offices = await lookupPincode(pin);
    if (!offices.length) {
      return NextResponse.json(
        { ok: false, error: "PIN code not found. You can still enter address manually." },
        { status: 404 },
      );
    }
    const primary = offices[0];
    return NextResponse.json({
      ok: true,
      pincode: primary.pincode,
      state: primary.state,
      district: primary.district,
      offices: offices.map((o) => ({
        office_name: o.office_name,
        district: o.district,
        state: o.state,
        office_type: o.office_type,
      })),
    });
  } catch (e) {
    console.error(e);
    return NextResponse.json(
      { ok: false, error: "Unable to look up PIN code right now." },
      { status: 500 },
    );
  }
}
