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 {
  RoutingNotFoundError,
  RoutingNotActivatableError,
  OperationRequiredError,
  DuplicateOperationSequenceError,
  WorkCenterNotActiveError,
  CrossCompanyWorkCenterError,
} from "../lib/errors.generated";
import {
  baseDraftRouting,
  baseActiveRouting,
  baseRoutingOperation,
  baseActiveWorkCenter,
  baseInactiveWorkCenter,
} from "../testing/fixtures";
import { run } from "./activateRouting";

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

  const validInput = { id: "routing-1" };

  it("activates a valid draft routing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseDraftRouting],
      [baseRoutingOperation],
      [baseActiveWorkCenter],
      [{ ...baseDraftRouting, status: "ACTIVE" }],
    );

    const result = await mock.withTx((trx) => run(trx, validInput, ctx));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.routing.status).toBe("ACTIVE");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

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

    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, validInput, ctx));

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

  it("returns error when the routing is not in DRAFT", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseActiveRouting]);

    const result = await mock.withTx((trx) => run(trx, { id: "routing-2" }, ctx));

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

  it("returns error when the routing has no operations", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseDraftRouting], []);

    const result = await mock.withTx((trx) => run(trx, validInput, ctx));

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

  it("returns error when operation sequence numbers are duplicated", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseDraftRouting],
      [baseRoutingOperation, { ...baseRoutingOperation, id: "operation-dup", sequenceNumber: 10 }],
    );

    const result = await mock.withTx((trx) => run(trx, validInput, ctx));

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

  it("returns error when a referenced work center is inactive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseDraftRouting], [baseRoutingOperation], [baseInactiveWorkCenter]);

    const result = await mock.withTx((trx) => run(trx, validInput, ctx));

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

  it("returns error when a referenced work center is outside the routing company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseDraftRouting],
      [baseRoutingOperation],
      [
        {
          ...baseActiveWorkCenter,
          companyId: "other-company",
        },
      ],
    );

    const result = await mock.withTx((trx) => run(trx, validInput, ctx));

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