import { NextResponse } from "next/server";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { CarrierShipmentNotFoundError } from "../../lib/shipping-service.js";
import { shippingCarrierUpstreamErrorResponse } from "../../lib/upstream-error-response.js";
import { trackingQuerySchema } from "../../data/validators.js";
import { shippingCarriersTag } from "../openapi.js";
const metadata = {
  path: "/shipping-carriers/tracking",
  GET: { requireAuth: true, requireFeatures: ["shipping_carriers.view"] }
};
async function GET(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth?.tenantId || !auth.orgId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const url = new URL(req.url);
  const parsed = trackingQuerySchema.safeParse({
    providerKey: url.searchParams.get("providerKey"),
    shipmentId: url.searchParams.get("shipmentId") ?? void 0,
    trackingNumber: url.searchParams.get("trackingNumber") ?? void 0
  });
  if (!parsed.success) {
    return NextResponse.json({ error: "Invalid query", details: parsed.error.flatten() }, { status: 422 });
  }
  const container = await createRequestContainer();
  const service = container.resolve("shippingCarrierService");
  try {
    const tracking = await service.getTracking({
      ...parsed.data,
      organizationId: auth.orgId,
      tenantId: auth.tenantId
    });
    return NextResponse.json(tracking);
  } catch (error) {
    if (error instanceof CarrierShipmentNotFoundError) {
      return NextResponse.json({ error: error.message }, { status: 404 });
    }
    return shippingCarrierUpstreamErrorResponse("tracking.get", error);
  }
}
const openApi = {
  tags: [shippingCarriersTag],
  summary: "Get tracking",
  methods: {
    GET: {
      summary: "Get tracking",
      tags: [shippingCarriersTag],
      responses: [
        { status: 200, description: "Tracking returned" },
        { status: 404, description: "Shipment not found" },
        { status: 422, description: "Validation failed" },
        { status: 502, description: "Provider upstream error" }
      ]
    }
  }
};
export {
  GET,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
