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

    const result = await run(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 { db, spies } = createMockDb<DB>();
    const lines = [
      { ...correctionIncreaseLine, stockAdjustmentId: baseSubmittedAdjustment.id },
      { ...correctionDecreaseLine, stockAdjustmentId: baseSubmittedAdjustment.id },
    ];

    spies.select
      .mockReturnValueOnce(baseSubmittedAdjustment) // StockAdjustment
      .mockReturnValueOnce(lines); // StockAdjustmentLines

    const result = await run(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 { db, spies } = createMockDb<DB>();

    spies.select
      .mockReturnValueOnce(baseSubmittedAdjustment) // StockAdjustment
      .mockReturnValueOnce([]); // No lines

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