import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { NoFilterProvidedError } from "../lib/errors.generated";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { baseStockLevel, baseStockReservation } from "../testing/fixtures";
import { run } from "./listStockLevels";

describe("listStockLevels", () => {
  it("lists stock levels by item across all locations", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseStockLevel]);

    const result = await run(mock.db, { itemId: "item-1" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
    expect(items[0]).toMatchObject(baseStockLevel);
  });

  it("lists stock levels by storage location", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseStockLevel]);

    const result = await run(mock.db, { storageLocationId: "location-1" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
    expect(items[0]).toMatchObject(baseStockLevel);
  });

  it("lists stock levels by site (aggregates all locations)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    // First select: StorageLocation ids by siteId
    // Second select: StockLevel where storageLocationId in those ids
    mock.enqueueResults([{ id: "location-1" }], [baseStockLevel]);

    const result = await run(mock.db, { siteId: "site-1" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
    expect(items[0]).toMatchObject(baseStockLevel);
  });

  it("returns empty list when no matches", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { itemId: "non-existent" });
    const { items, hasNextPage } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(
      result as never,
    );

    expect(items).toHaveLength(0);
    expect(hasNextPage).toBe(false);
  });

  it("returns error when no filter is provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await run(mock.db, {});
    expectErr(result as never, NoFilterProvidedError);
  });

  it("includes computed available quantity", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseStockLevel]);

    const result = await run(mock.db, { itemId: "item-1" });
    const { items } = expectOk<{
      items: { stockType: string; quantity: string; availableQuantity: string }[];
      hasNextPage: boolean;
    }>(result as never);

    expect(items[0].stockType).toBe("AVAILABLE");
    expect(items[0].quantity).toBe("85");
    expect(items[0].availableQuantity).toBe("85");
  });

  it("sums multiple open reservations per item and location", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseStockLevel],
      [
        { ...baseStockReservation, storageLocationId: "location-1", reservedQuantity: "10" },
        {
          ...baseStockReservation,
          id: "stock-reservation-2",
          storageLocationId: "location-1",
          reservedQuantity: "5",
          consumedQuantity: "2",
        },
      ],
    );

    const result = await run(mock.db, { itemId: "item-1" });
    const { items } = expectOk<{
      items: { availableQuantity: string }[];
      hasNextPage: boolean;
    }>(result as never);

    expect(items[0].availableQuantity).toBe("72");
  });
});
