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

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

  it("resumes a paused work order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const resumedWorkOrder = {
      ...basePausedWorkOrder,
      status: "IN_PROGRESS" as const,
      pauseReason: null,
    };

    mock.enqueueResults(
      [basePausedWorkOrder],
      [baseInProgressProductionOrder],
      [resumedWorkOrder],
      [],
    );

    const result = await mock.withTx((trx) => run(trx, { 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(mock.updates.length).toBeGreaterThan(0);
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("returns error when the work order does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePendingWorkOrder]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([basePausedWorkOrder], [baseDraftProductionOrder]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const resumedWorkOrder = {
      ...basePausedWorkOrder,
      status: "IN_PROGRESS" as const,
      pauseReason: null,
      completedQuantity: basePausedWorkOrder.completedQuantity,
      scrapQuantity: basePausedWorkOrder.scrapQuantity,
      actualSetupTime: basePausedWorkOrder.actualSetupTime,
      actualRunTime: basePausedWorkOrder.actualRunTime,
    };

    mock.enqueueResults(
      [basePausedWorkOrder],
      [baseInProgressProductionOrder],
      [resumedWorkOrder],
      [],
    );

    const result = await mock.withTx((trx) => run(trx, { 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);
    }
  });
});
