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,
  RoutingNotDeactivatableError,
  ReplacementRequiredError,
} from "../lib/errors.generated";
import {
  baseActiveRouting,
  baseDraftRouting,
  baseReleasedProductionOrder,
} from "../testing/fixtures";
import { run } from "./deactivateRouting";

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

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

  it("deactivates an active routing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseActiveRouting],
      [{ ...baseActiveRouting, id: "routing-4" }],
      [{ ...baseActiveRouting, status: "INACTIVE" }],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.routing.status).toBe("INACTIVE");
    }
    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, { id: "nonexistent" }, ctx));

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

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

    mock.enqueueResults([baseDraftRouting]);

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

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

  it("returns error when replacement policy blocks deactivation", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseActiveRouting],
      [],
      [
        {
          ...baseReleasedProductionOrder,
          selectedRoutingRevisionId: "routing-2",
        },
      ],
    );

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

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

  it("preserves released operation snapshots after deactivation", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseActiveRouting],
      [{ ...baseActiveRouting, id: "routing-4" }],
      [{ ...baseActiveRouting, status: "INACTIVE" }],
    );

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

    // Deactivation only updates the Routing status,
    // not ProductionOrderRoutingSnapshot, preserving frozen snapshots.
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.routing.status).toBe("INACTIVE");
    }
  });
});
