import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseGoodsReceiptExecution], [baseGoodsReceiptExecutionLine]);

    const result = await run(mock.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(mock.selects[0].parameters).toContain("GOODS_RECEIPT");
    expect(mock.selects[0].sql).toMatch(/"executionType"/);
  });

  it("returns null when goods receipt execution does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseGoodsReceiptExecution], []);

    const result = await run(mock.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);
  });
});
