import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { WorkOrderNotFoundError } from "../lib/errors.generated";
import {
  baseInProgressWorkOrder,
  basePausedWorkOrder,
  baseStartedEvent,
  baseProgressEvent,
} from "../testing/fixtures";
import { expectOk, expectErr } from "../testing/commandTestUtils";
import { run } from "./getWorkOrder";

describe("getWorkOrder", () => {
  it("returns a work order with execution history when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseInProgressWorkOrder);
    spies.select.mockReturnValueOnce([baseStartedEvent, baseProgressEvent]);

    const result = await run(db, { id: baseInProgressWorkOrder.id });
    const { workOrder, executionEvents } = expectOk<{
      workOrder: { id: string; status: string };
      executionEvents: unknown[];
    }>(result as never);

    expect(workOrder.id).toBe(baseInProgressWorkOrder.id);
    expect(workOrder.status).toBe("IN_PROGRESS");
    expect(executionEvents).toHaveLength(2);
  });

  it("returns paused work orders with prior pause data", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(basePausedWorkOrder);
    spies.select.mockReturnValueOnce([baseStartedEvent]);

    const result = await run(db, { id: basePausedWorkOrder.id });
    const { workOrder, executionEvents } = expectOk<{
      workOrder: { id: string; status: string; pauseReason: string | null };
      executionEvents: unknown[];
    }>(result as never);

    expect(workOrder.status).toBe("PAUSED");
    expect(workOrder.pauseReason).toBeDefined();
    expect(executionEvents).toHaveLength(1);
  });

  it("returns a work order with handoff evidence and parent order context", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseInProgressWorkOrder);
    spies.select.mockReturnValueOnce([baseStartedEvent]);

    const result = await run(db, { id: baseInProgressWorkOrder.id });
    const { workOrder } = expectOk<{
      workOrder: {
        id: string;
        productionOrderId: string;
        workCenterId: string;
      };
      executionEvents: unknown[];
    }>(result as never);

    expect(workOrder.productionOrderId).toBe(baseInProgressWorkOrder.productionOrderId);
    expect(workOrder.workCenterId).toBe(baseInProgressWorkOrder.workCenterId);
  });

  it("returns error when the work order does not exist", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "nonexistent" });
    expectErr(result as never, WorkOrderNotFoundError);
  });
});
