import { createRoute } from "../../../modules/api-utils/createRoute";
import { procurement } from "../../../managers/procurement";
import { apiResponse } from "../../../modules/api-utils/apiResponse";
import { prisma } from "../../../constants";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../../middleware/authorization";

/* GET /v1/procurement/items/:identifier/inventory */
export default createRoute(
    "get",
    ["/items/:identifier/inventory"],
    async (c) => {
        const identifier = c.req.param("identifier");
        const includeWarehouse = c.req.query("includeWarehouse") === "true";
        const includeWarehouseBin = c.req.query("includeWarehouseBin") === "true";
        const item = await procurement.fetchItem(identifier);

        const rows = await prisma.productInventory.findMany({
            where: { itemId: item.cwCatalogId },
            include: {
                warehouse: includeWarehouse,
                warehouseBin: includeWarehouseBin,
            },
            orderBy: [{ warehouseId: "asc" }, { warehouseBinId: "asc" }],
        });

        const data = rows.map((row) => ({
            id: row.id,
            qtyOnHand: row.qtyOnHand,
            warehouseId: row.warehouseId,
            warehouseBinId: row.warehouseBinId,
            ...(includeWarehouse && {
                warehouse: (row as any).warehouse
                    ? { id: (row as any).warehouse.id, name: (row as any).warehouse.name }
                    : null,
            }),
            ...(includeWarehouseBin && {
                warehouseBin: (row as any).warehouseBin
                    ? { id: (row as any).warehouseBin.id, name: (row as any).warehouseBin.name }
                    : null,
            }),
        }));

        const response = apiResponse.successful(
            "Product inventory fetched successfully!",
            data,
        );

        return c.json(response, response.status as ContentfulStatusCode);
    },
    authMiddleware({ permissions: ["procurement.catalog.fetch"] }),
);
