import { NextResponse } from "next/server";

import { requirePermission } from "@/src/lib/auth/requireSession";
import { searchPriceOffers } from "@/src/lib/price-search";
import type { PriceSearchRequest } from "@/src/types/priceSearch";

export async function POST(request: Request) {
  const session = await requirePermission(
    (p) => p.canSearchPrices,
    "Non hai i permessi per la ricerca prezzi",
  );
  if (session instanceof NextResponse) return session;

  try {
    const body = (await request.json()) as Partial<PriceSearchRequest>;

    const descrizione = String(body.descrizione ?? "").trim();
    if (!descrizione) {
      return NextResponse.json(
        { error: "La descrizione e obbligatoria per la ricerca" },
        { status: 400 },
      );
    }

    const payload: PriceSearchRequest = {
      descrizione,
      barcode: body.barcode ?? null,
      codice: body.codice ?? null,
      quantita:
        body.quantita !== undefined && body.quantita !== null
          ? Number(body.quantita)
          : undefined,
    };

    const result = await searchPriceOffers(payload, {
      userId: session.user.id,
      userName: session.user.utente || session.user.name || session.user.email || undefined,
    });

    return NextResponse.json(result);
  } catch (error) {
    console.error("[API ricerca-prezzi]", error);
    const message =
      error instanceof Error ? error.message : "Errore ricerca prezzi";

    const status = message.includes("non configurata") ? 503 : 502;

    return NextResponse.json({ error: message }, { status });
  }
}
