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 {
  baseSubmittedAdjustment,
  correctionIncreaseLine,
  correctionDecreaseLine,
} from "../testing/fixtures";
import { run } from "./getStockAdjustment";

describe("getStockAdjustment", () => {
  it("returns null when not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { id: "nonexistent" });
    const value = expectOk<{
      stockAdjustment: null;
      stockAdjustmentLines: unknown[];
    }>(result as never);

    expect(value.stockAdjustment).toBeNull();
    expect(value.stockAdjustmentLines).toHaveLength(0);
  });

  it("returns stock adjustment with lines when found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const lines = [
      { ...correctionIncreaseLine, stockAdjustmentId: baseSubmittedAdjustment.id },
      { ...correctionDecreaseLine, stockAdjustmentId: baseSubmittedAdjustment.id },
    ];

    mock.enqueueResults([baseSubmittedAdjustment], lines);

    const result = await run(mock.db, { id: baseSubmittedAdjustment.id });
    const value = expectOk<{
      stockAdjustment: { id: string; adjustmentType: string };
      stockAdjustmentLines: { id: string }[];
    }>(result as never);

    expect(value.stockAdjustment).toMatchObject({ id: baseSubmittedAdjustment.id });
    expect(value.stockAdjustment.adjustmentType).toBe("CORRECTION");
    expect(value.stockAdjustmentLines).toHaveLength(2);
  });

  it("returns stockAdjustment with empty lines when no lines exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseSubmittedAdjustment], []);

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

    expect(value.stockAdjustment).toMatchObject({ id: baseSubmittedAdjustment.id });
    expect(value.stockAdjustmentLines).toHaveLength(0);
  });
});
