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

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

  it("starts a pending work order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const startedWorkOrder = {
      ...basePendingWorkOrder,
      status: "IN_PROGRESS" as const,
      actualStartDate: new Date(),
    };

    // work order lookup
    spies.select.mockReturnValueOnce(basePendingWorkOrder);
    // parent production order lookup
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // sibling work orders (no predecessors)
    spies.select.mockReturnValueOnce([basePendingWorkOrder]);
    // update work order
    spies.update.mockReturnValueOnce(startedWorkOrder);
    // insert execution event
    spies.insert.mockReturnValueOnce(undefined);
    // update parent production order to IN_PROGRESS
    spies.update.mockReturnValueOnce(undefined);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workOrder.status).toBe("IN_PROGRESS");
    }
    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 pending", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseInProgressWorkOrder);

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

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

  it("returns error when the parent production order is not executable", async () => {
    const { db, spies } = createMockDb<Transaction>();

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

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

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

  it("returns error when required predecessor work is incomplete", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const secondWorkOrder = {
      ...basePendingWorkOrder,
      id: "work-order-second",
      routingOperationSequenceNumber: 20,
    };

    // work order lookup (second operation)
    spies.select.mockReturnValueOnce(secondWorkOrder);
    // parent production order
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // sibling work orders - first is still PENDING
    spies.select.mockReturnValueOnce([basePendingWorkOrder, secondWorkOrder]);

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

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