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

describe("getInventoryAdjustment", () => {
  it("returns adjustment when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseDraftAdjustment);

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

    expect(adjustment).not.toBeNull();
    expect(adjustment).toMatchObject({ id: baseDraftAdjustment.id });
  });

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

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

    expect(adjustment).toBeNull();
  });

  it("includes status and reason code", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseDraftAdjustment);

    const result = await run(db, { id: baseDraftAdjustment.id });
    const { adjustment } = expectOk<{
      adjustment: { status: string; reasonCode: string };
    }>(result as never);

    expect(adjustment.status).toBe("DRAFT");
    expect(adjustment.reasonCode).toBe("damage");
  });

  it("includes optional lot and serial number references", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseDraftAdjustment);

    const result = await run(db, { id: baseDraftAdjustment.id });
    const { adjustment } = expectOk<{
      adjustment: {
        lotId: string | null;
        serialNumberId: string | null;
      };
    }>(result as never);

    expect(adjustment.lotId).toBeNull();
    expect(adjustment.serialNumberId).toBeNull();
  });
});
