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 {
  BomNotFoundError,
  BomNotDeactivatableError,
  ReplacementRequiredError,
} from "../lib/errors.generated";
import { baseDraftBom, baseActiveBom } from "../testing/fixtures";
import { run } from "./deactivateBillOfMaterial";

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

  it("deactivates an active BOM", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivatedBom = { ...baseActiveBom, status: "INACTIVE" as const };

    mock.enqueueResults(
      [baseActiveBom],
      [{ ...baseActiveBom, id: "bom-replacement" }],
      [deactivatedBom],
    );

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

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

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

    mock.enqueueResults([]);

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

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

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

    mock.enqueueResults([baseDraftBom]);

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

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

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

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

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

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

  it("preserves released production-order snapshots after deactivation", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivatedBom = { ...baseActiveBom, status: "INACTIVE" as const };

    mock.enqueueResults(
      [baseActiveBom],
      [{ ...baseActiveBom, id: "bom-replacement" }],
      [deactivatedBom],
    );

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

    // Verify that the command only updates the BOM status —
    // it does not touch ProductionOrderBomSnapshot at all
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.billOfMaterial.status).toBe("INACTIVE");
    }
    // The update should only have been called once (for BOM status)
    expect(mock.updates).toHaveLength(1);
  });
});
