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

describe("getGoodsReceipt", () => {
  it("returns goods receipt execution with lines when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select
      .mockReturnValueOnce(baseGoodsReceiptExecution)
      .mockReturnValueOnce([baseGoodsReceiptExecutionLine]);

    const result = await run(db, { id: baseGoodsReceiptExecution.id });
    const value = expectOk<{
      inventoryExecution: { id: string; executionType: string };
      inventoryExecutionLines: unknown[];
    }>(result as never);

    expect(value.inventoryExecution).toMatchObject({
      id: baseGoodsReceiptExecution.id,
      executionType: "GOODS_RECEIPT",
    });
    expect(value.inventoryExecutionLines).toHaveLength(1);
    expect(spies.where).toHaveBeenCalledWith("executionType", "=", "GOODS_RECEIPT");
  });

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

    const result = await run(db, { id: "missing" });
    const value = expectOk<{
      inventoryExecution: null;
      inventoryExecutionLines: unknown[];
    }>(result as never);

    expect(value.inventoryExecution).toBeNull();
    expect(value.inventoryExecutionLines).toHaveLength(0);
  });

  it("returns goods receipt execution with empty lines when no lines exist", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseGoodsReceiptExecution).mockReturnValueOnce([]);

    const result = await run(db, { id: baseGoodsReceiptExecution.id });
    const value = expectOk<{
      inventoryExecution: { id: string };
      inventoryExecutionLines: unknown[];
    }>(result as never);

    expect(value.inventoryExecution).toMatchObject({ id: baseGoodsReceiptExecution.id });
    expect(value.inventoryExecutionLines).toHaveLength(0);
  });
});
