import { NextResponse } from "next/server";
import { randomUUID } from "node:crypto";
import { getBotSbisItem, getBotSbisPrices } from "@/lib/bot-api";
import { adminAuthorized } from "@/lib/admin-auth";

function fail(error: string, status = 400) {
  return NextResponse.json({ error }, { status });
}
function nullableText(value: unknown) {
  return typeof value === "string"
    ? value
    : value == null
      ? null
      : String(value);
}
function nullableNumber(value: unknown) {
  const number = Number(value);
  return value == null || value === "" || !Number.isFinite(number)
    ? null
    : number;
}

/**
 * Admin view of the full SBIS item card (contract §3в.2): composition with
 * Qty/NetQty/Output, explicit root Output as weight, and the price list id
 * chosen by the bot (SBIS_PRICE_ID).
 */
export async function GET(request: Request) {
  if (!(await adminAuthorized(request))) return fail("Unauthorized", 401);
  const params = new URL(request.url).searchParams;
  const requestId = randomUUID();
  try {
    if (params.get("prices") === "1") {
      const prices = await getBotSbisPrices();
      return NextResponse.json(
        { defaultId: prices.default_id, prices: prices.prices },
        { headers: { "Cache-Control": "no-store" } },
      );
    }
    const sbisId = (params.get("sbisId") || "").trim();
    if (!/^\d+$/.test(sbisId)) return fail("Укажите числовой sbis_id");
    const item = await getBotSbisItem(sbisId);
    const composition = Array.isArray(item.composition)
      ? item.composition.map((row) => ({
          name: nullableText(row?.name),
          quantity: nullableNumber(row?.quantity),
          net_g: nullableNumber(row?.net_g),
          output: nullableNumber(row?.output),
          unit: nullableText(row?.unit),
        }))
      : [];
    return NextResponse.json(
      {
        requestId,
        sbisId: Number(item.sbis_id),
        name: nullableText(item.name),
        description: nullableText(item.description),
        productionVolume: nullableNumber(item.production_volume),
        productionMeasure: nullableText(item.production_measure),
        weight: nullableNumber(item.weight),
        weightStatus: nullableText(item.weight_status) || "unknown",
        composition,
        nutrition: {
          calories_kcal: nullableNumber(item.nutrition?.calories_kcal),
          protein_g: nullableNumber(item.nutrition?.protein_g),
          fat_g: nullableNumber(item.nutrition?.fat_g),
          carbohydrate_g: nullableNumber(item.nutrition?.carbohydrate_g),
          source: nullableText(item.nutrition?.source) || "not_present",
        },
        priceListId: nullableNumber(item.price_list?.id),
        updatedAt: nullableText(item.updated_at) || new Date().toISOString(),
      },
      { headers: { "Cache-Control": "no-store", "X-Request-Id": requestId } },
    );
  } catch (error) {
    const status =
      typeof (error as { status?: unknown })?.status === "number"
        ? Number((error as { status: number }).status)
        : 502;
    console.error("sbis_item_card_failed", {
      requestId,
      sbisId: params.get("sbisId"),
      status,
      phase: "fetch_or_normalize",
    });
    return NextResponse.json(
      {
        error:
          error instanceof Error ? error.message : "Карточка СБИС недоступна",
        requestId,
      },
      {
        status,
        headers: { "Cache-Control": "no-store", "X-Request-Id": requestId },
      },
    );
  }
}
