import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  BomNotFoundError,
  BomNotDeactivatableError,
  ReplacementRequiredError,
} from "../lib/errors.generated";
import { baseDraftBom, baseActiveBom } from "../testing/fixtures";
import { run } from "./deactivateBillOfMaterial";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("deactivates an active BOM", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivatedBom = { ...baseActiveBom, status: "INACTIVE" as const };

    // BOM exists and is ACTIVE, with defaultSelection = true
    spies.select.mockReturnValueOnce(baseActiveBom);
    // replacement BOM exists
    spies.select.mockReturnValueOnce({ ...baseActiveBom, id: "bom-replacement" });
    // update to INACTIVE
    spies.update.mockReturnValue(deactivatedBom);

    const result = await run(db, { id: "bom-2" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.billOfMaterial.status).toBe("INACTIVE");
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("returns error when the BOM does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(baseDraftBom);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();

    // BOM exists and is ACTIVE with default selection
    spies.select.mockReturnValueOnce(baseActiveBom);
    // no replacement BOM
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    const deactivatedBom = { ...baseActiveBom, status: "INACTIVE" as const };

    // BOM exists and is ACTIVE with default selection
    spies.select.mockReturnValueOnce(baseActiveBom);
    // replacement BOM exists
    spies.select.mockReturnValueOnce({ ...baseActiveBom, id: "bom-replacement" });
    // update to INACTIVE
    spies.update.mockReturnValue(deactivatedBom);

    const result = await run(db, { 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(spies.update).toHaveBeenCalledTimes(1);
  });
});
