import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseGoodsReceipt, baseGoodsReceiptLines } from "../testing/fixtures";
import { expectOk } from "../testing/commandTestUtils";
import { run } from "./getGoodsReceipt";

describe("getGoodsReceipt", () => {
  it("returns goods receipt when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseGoodsReceipt);

    const result = await run(db, { id: baseGoodsReceipt.id });
    const { goodsReceipt } = expectOk<{ goodsReceipt: unknown }>(result as never);

    expect(goodsReceipt).not.toBeNull();
    expect(goodsReceipt).toMatchObject({ id: baseGoodsReceipt.id });
  });

  it("returns receipt lines and handoff metadata with the receipt", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseGoodsReceipt);

    const result = await run(db, { id: baseGoodsReceipt.id });
    const { goodsReceipt } = expectOk<{
      goodsReceipt: { lines: unknown[]; inventoryHandoff: unknown };
    }>(result as never);

    expect(goodsReceipt.lines).toEqual(baseGoodsReceiptLines);
    expect(goodsReceipt.inventoryHandoff).toBeNull();
  });

  it("returns null when goods receipt does not exist", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "nonexistent-id" });
    const { goodsReceipt } = expectOk<{ goodsReceipt: unknown }>(result as never);

    expect(goodsReceipt).toBeNull();
  });
});
