import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  WorkOrderNotFoundError,
  WorkOrderNotPausableError,
  PauseReasonRequiredError,
} from "../lib/errors.generated";
import { baseInProgressWorkOrder, basePendingWorkOrder } from "../testing/fixtures";
import { run } from "./pauseWorkOrder";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

describe("pauseWorkOrder", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["manufacturing:pauseWorkOrder"],
  };

  it("pauses an in-progress work order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const pausedWorkOrder = {
      ...baseInProgressWorkOrder,
      status: "PAUSED" as const,
      pauseReason: "Machine maintenance",
    };

    // work order lookup
    spies.select.mockReturnValueOnce(baseInProgressWorkOrder);
    // update work order
    spies.update.mockReturnValueOnce(pausedWorkOrder);
    // insert execution event
    spies.insert.mockReturnValueOnce(undefined);

    const result = await run(
      db,
      { id: baseInProgressWorkOrder.id, pauseReason: "Machine maintenance" },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workOrder.status).toBe("PAUSED");
      expect(result.value.workOrder.pauseReason).toBe("Machine maintenance");
    }
    expect(spies.update).toHaveBeenCalled();
    expect(spies.insert).toHaveBeenCalled();
  });

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

    const result = await run(db, { id: "nonexistent", pauseReason: "Some reason" }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(WorkOrderNotFoundError);
    }
  });

  it("returns error when the work order is not in progress", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePendingWorkOrder);

    const result = await run(db, { id: basePendingWorkOrder.id, pauseReason: "Some reason" }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(WorkOrderNotPausableError);
    }
  });

  it("returns error when no pause reason is provided", async () => {
    const { db } = createMockDb<Transaction>();

    const result = await run(db, { id: baseInProgressWorkOrder.id, pauseReason: "" }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(PauseReasonRequiredError);
    }
  });

  it("preserves prior execution quantities and time after pause", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const pausedWorkOrder = {
      ...baseInProgressWorkOrder,
      status: "PAUSED" as const,
      pauseReason: "Break time",
      completedQuantity: baseInProgressWorkOrder.completedQuantity,
      scrapQuantity: baseInProgressWorkOrder.scrapQuantity,
      actualSetupTime: baseInProgressWorkOrder.actualSetupTime,
      actualRunTime: baseInProgressWorkOrder.actualRunTime,
    };

    // work order lookup
    spies.select.mockReturnValueOnce(baseInProgressWorkOrder);
    // update work order
    spies.update.mockReturnValueOnce(pausedWorkOrder);
    // insert execution event
    spies.insert.mockReturnValueOnce(undefined);

    const result = await run(
      db,
      { id: baseInProgressWorkOrder.id, pauseReason: "Break time" },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workOrder.completedQuantity).toBe(
        baseInProgressWorkOrder.completedQuantity,
      );
      expect(result.value.workOrder.actualSetupTime).toBe(baseInProgressWorkOrder.actualSetupTime);
      expect(result.value.workOrder.actualRunTime).toBe(baseInProgressWorkOrder.actualRunTime);
    }
  });
});
