import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  WorkOrderNotFoundError,
  WorkOrderNotResumableError,
  ParentOrderNotExecutableError,
} from "../lib/errors.generated";
import {
  basePausedWorkOrder,
  basePendingWorkOrder,
  baseInProgressProductionOrder,
  baseDraftProductionOrder,
} from "../testing/fixtures";
import { run } from "./resumeWorkOrder";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("resumes a paused work order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const resumedWorkOrder = {
      ...basePausedWorkOrder,
      status: "IN_PROGRESS" as const,
      pauseReason: null,
    };

    // work order lookup
    spies.select.mockReturnValueOnce(basePausedWorkOrder);
    // parent production order lookup
    spies.select.mockReturnValueOnce(baseInProgressProductionOrder);
    // update work order
    spies.update.mockReturnValueOnce(resumedWorkOrder);
    // insert execution event
    spies.insert.mockReturnValueOnce(undefined);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workOrder.status).toBe("IN_PROGRESS");
      expect(result.value.workOrder.pauseReason).toBeNull();
    }
    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" }, ctx);

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

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

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

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

  it("returns error when the parent production order no longer allows execution", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // work order lookup
    spies.select.mockReturnValueOnce(basePausedWorkOrder);
    // parent production order - DRAFT is not executable
    spies.select.mockReturnValueOnce(baseDraftProductionOrder);

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

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

  it("preserves prior execution history after resume", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const resumedWorkOrder = {
      ...basePausedWorkOrder,
      status: "IN_PROGRESS" as const,
      pauseReason: null,
      completedQuantity: basePausedWorkOrder.completedQuantity,
      scrapQuantity: basePausedWorkOrder.scrapQuantity,
      actualSetupTime: basePausedWorkOrder.actualSetupTime,
      actualRunTime: basePausedWorkOrder.actualRunTime,
    };

    // work order lookup
    spies.select.mockReturnValueOnce(basePausedWorkOrder);
    // parent production order lookup
    spies.select.mockReturnValueOnce(baseInProgressProductionOrder);
    // update work order
    spies.update.mockReturnValueOnce(resumedWorkOrder);
    // insert execution event
    spies.insert.mockReturnValueOnce(undefined);

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

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