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 { baseGoodsIssueExecution, baseGoodsIssueExecutionLine } from "../testing/fixtures";
import { run } from "./getGoodsIssue";

describe("getGoodsIssue", () => {
  it("returns goods issue execution with lines when found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseGoodsIssueExecution], [baseGoodsIssueExecutionLine]);

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

    expect(value.inventoryExecution).toMatchObject({
      id: baseGoodsIssueExecution.id,
      executionType: "GOODS_ISSUE",
    });
    expect(value.inventoryExecutionLines).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain("GOODS_ISSUE");
    expect(mock.selects[0].sql).toMatch(/"executionType"/);
  });

  it("returns null when goods issue 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 issue execution with empty lines when no lines exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseGoodsIssueExecution], []);

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

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