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

describe("getStockMovement", () => {
  it("returns stock movement when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseDraftMovement);
    spies.select.mockReturnValueOnce([baseMoveLine]);

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

    expect(stockMovement).not.toBeNull();
    expect(stockMovement).toMatchObject({ id: baseDraftMovement.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 { stockMovement, stockMoveLines } = expectOk<{
      stockMovement: unknown;
      stockMoveLines: unknown[];
    }>(result as never);

    expect(stockMovement).toBeNull();
    expect(stockMoveLines).toEqual([]);
  });

  it("includes all movement lines", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseDraftMovement);
    spies.select.mockReturnValueOnce([baseMoveLine]);

    const result = await run(db, { id: baseDraftMovement.id });
    const { stockMoveLines } = expectOk<{ stockMoveLines: unknown[] }>(result as never);

    expect(stockMoveLines).toHaveLength(1);
  });

  it("includes source and destination locations per line", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseDraftMovement);
    spies.select.mockReturnValueOnce([baseMoveLine]);

    const result = await run(db, { id: baseDraftMovement.id });
    const { stockMoveLines } = expectOk<{
      stockMoveLines: {
        sourceLocationId: string | null;
        destinationLocationId: string | null;
      }[];
    }>(result as never);

    expect(stockMoveLines[0].sourceLocationId).toBeNull();
    expect(stockMoveLines[0].destinationLocationId).toBe("location-1");
  });
});
