import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } 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 { db, spies } = createMockDb<DB>();
    spies.select
      .mockReturnValueOnce(baseGoodsIssueExecution)
      .mockReturnValueOnce([baseGoodsIssueExecutionLine]);

    const result = await run(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(spies.where).toHaveBeenCalledWith("executionType", "=", "GOODS_ISSUE");
  });

  it("returns null when goods issue 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 issue execution with empty lines when no lines exist", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseGoodsIssueExecution).mockReturnValueOnce([]);

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