import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  BomNotFoundError,
  BomNotActivatableError,
  ComponentLineRequiredError,
  ComponentItemInactiveError,
  CircularBomReferenceError,
  EffectivityConflictError,
} from "../lib/errors.generated";
import { baseDraftBom, baseActiveBom, baseBomLine } from "../testing/fixtures";
import { run } from "./activateBillOfMaterial";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("activates a valid draft BOM", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activatedBom = { ...baseDraftBom, status: "ACTIVE" as const };

    // BOM exists and is DRAFT
    spies.select.mockReturnValueOnce(baseDraftBom);
    // lines exist
    spies.select.mockReturnValueOnce([baseBomLine]);
    // component item exists (active)
    spies.select.mockReturnValueOnce({ id: "item-2" });
    // no conflicting active BOM
    spies.select.mockReturnValueOnce(undefined);
    // update to ACTIVE
    spies.update.mockReturnValue(activatedBom);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.billOfMaterial.status).toBe("ACTIVE");
    }
    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 in DRAFT", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(baseActiveBom);

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

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

  it("returns error when the BOM has no component lines", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // BOM exists and is DRAFT
    spies.select.mockReturnValueOnce(baseDraftBom);
    // no lines
    spies.select.mockReturnValueOnce([]);

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

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

  it("returns error when a component item is inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // BOM exists and is DRAFT
    spies.select.mockReturnValueOnce(baseDraftBom);
    // lines exist
    spies.select.mockReturnValueOnce([baseBomLine]);
    // component item not found (inactive)
    spies.select.mockReturnValueOnce(undefined);

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

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

  it("returns error when a circular manufactured-item structure is detected", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const bomWithSubassembly = {
      ...baseDraftBom,
    };
    const subassemblyLine = {
      ...baseBomLine,
      isSubassembly: true,
      itemId: "item-sub",
    };

    // BOM exists and is DRAFT
    spies.select.mockReturnValueOnce(bomWithSubassembly);
    // lines with subassembly
    spies.select.mockReturnValueOnce([subassemblyLine]);
    // component item exists
    spies.select.mockReturnValueOnce({ id: "item-sub" });
    // child BOMs exist for subassembly item (execute returns array)
    spies.select.mockReturnValueOnce([
      {
        ...baseDraftBom,
        id: "child-bom",
        parentItemId: "item-sub",
      },
    ]);
    // child BOM lines reference back to parent item (circular)
    spies.select.mockReturnValueOnce([{ ...baseBomLine, itemId: "item-1" }]);

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

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

  it("returns error when activation would create an effectivity conflict", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // BOM exists and is DRAFT with default selection
    spies.select.mockReturnValueOnce(baseDraftBom);
    // lines exist
    spies.select.mockReturnValueOnce([baseBomLine]);
    // component item exists
    spies.select.mockReturnValueOnce({ id: "item-2" });
    // conflicting active BOM with same parent + default selection + no date bounds
    spies.select.mockReturnValueOnce({
      ...baseActiveBom,
      defaultSelection: true,
      effectivityStartDate: null,
      effectivityEndDate: null,
    });

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

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