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,
  WorkOrderNotStartableError,
  ParentOrderNotExecutableError,
  OperationSequenceBlockedError,
} from "../lib/errors.generated";
import {
  basePendingWorkOrder,
  baseInProgressWorkOrder,
  baseReleasedProductionOrder,
  baseDraftProductionOrder,
} from "../testing/fixtures";
import { run } from "./startWorkOrder";

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

  it("starts a pending work order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const startedWorkOrder = {
      ...basePendingWorkOrder,
      status: "IN_PROGRESS" as const,
      actualStartDate: new Date(),
    };

    mock.enqueueResults(
      [basePendingWorkOrder],
      [baseReleasedProductionOrder],
      [basePendingWorkOrder],
      [startedWorkOrder],
      [],
      [],
    );

    const result = await mock.withTx((trx) => run(trx, { id: basePendingWorkOrder.id }, ctx));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.workOrder.status).toBe("IN_PROGRESS");
    }
    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 pending", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseInProgressWorkOrder]);

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

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

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const secondWorkOrder = {
      ...basePendingWorkOrder,
      id: "work-order-second",
      routingOperationSequenceNumber: 20,
    };

    mock.enqueueResults(
      [secondWorkOrder],
      [baseReleasedProductionOrder],
      [basePendingWorkOrder, secondWorkOrder],
    );

    const result = await mock.withTx((trx) => run(trx, { id: secondWorkOrder.id }, ctx));

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