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

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

  const validInput = {
    id: "bom-1",
    bomType: "PHANTOM" as const,
    lines: [
      {
        itemId: "item-2",
        requiredQuantity: 3.0,
        unitOfMeasure: "EA",
      },
    ],
  };

  it("updates draft BOM metadata and component lines", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedBom = {
      ...baseDraftBom,
      bomType: "PHANTOM" as const,
    };

    // BOM exists and is DRAFT
    spies.select.mockReturnValueOnce(baseDraftBom);
    // component item exists
    spies.select.mockReturnValueOnce({ id: "item-2" });
    // update BOM header
    spies.update.mockReturnValueOnce(updatedBom);
    // delete old lines
    spies.delete.mockReturnValueOnce(undefined);
    // insert new line
    spies.insert.mockReturnValueOnce({ ...baseBomLine, requiredQuantity: 3.0 });

    const result = await run(db, validInput, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.billOfMaterial.bomType).toBe("PHANTOM");
    }
    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, validInput, 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, { ...validInput, id: "bom-2" }, ctx);

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

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

    spies.select.mockReturnValueOnce(baseDraftBom);

    const result = await run(
      db,
      {
        ...validInput,
        lines: [{ itemId: "item-2", requiredQuantity: -1, unitOfMeasure: "EA" }],
      },
      ctx,
    );

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

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

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

    const result = await run(db, validInput, ctx);

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

  it("returns error when effectivity changes would create ambiguous selection", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // BOM exists and is DRAFT
    spies.select.mockReturnValueOnce(baseDraftBom);
    // conflicting active BOM with same default selection
    spies.select.mockReturnValueOnce({
      ...baseActiveBom,
      defaultSelection: true,
      effectivityStartDate: null,
      effectivityEndDate: null,
    });

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

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