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

const receiptLedgerEntry = {
  id: "ledger-1",
  inventoryExecutionId: "execution-1",
  dcIndicator: "DR" as const,
  itemId: "item-1",
  storageLocationId: "location-1",
  quantity: 10,
  executedAt: new Date("2024-01-02T00:00:00.000Z"),
  lotId: "lot-1",
  serialNumberId: null,
  createdAt: new Date("2024-01-01T00:00:00.000Z"),
};

describe("traceLotBackward", () => {
  it("returns inbound movements for lot", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveLot], [receiptLedgerEntry]);

    const result = await run(mock.db, { lotId: "lot-1" });
    const { entries } = expectOk<{ entries: unknown[] }>(result as never);

    expect(entries).toHaveLength(1);
  });

  it("includes movement date and source reference", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveLot], [receiptLedgerEntry]);

    const result = await run(mock.db, { lotId: "lot-1" });
    const { entries } = expectOk<{
      entries: { executedAt: Date; storageLocationId: string }[];
    }>(result as never);

    expect(entries[0].executedAt).toEqual(new Date("2024-01-02T00:00:00.000Z"));
    expect(entries[0].storageLocationId).toBe("location-1");
  });

  it("returns error when lot not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { lotId: "non-existent" });

    expectErr(result as never, LotNotFoundError);
  });

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

    const result = await run(mock.db, { lotId: "lot-1" });
    const { entries } = expectOk<{ entries: unknown[] }>(result as never);

    expect(entries).toEqual([]);
  });
});
