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,
  WorkOrderNotPausableError,
  PauseReasonRequiredError,
} from "../lib/errors.generated";
import { baseInProgressWorkOrder, basePendingWorkOrder } from "../testing/fixtures";
import { run } from "./pauseWorkOrder";

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

  it("pauses an in-progress work order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const pausedWorkOrder = {
      ...baseInProgressWorkOrder,
      status: "PAUSED" as const,
      pauseReason: "Machine maintenance",
    };

    mock.enqueueResults([baseInProgressWorkOrder], [pausedWorkOrder], []);

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

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

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

    mock.enqueueResults([baseInProgressWorkOrder], [pausedWorkOrder], []);

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