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,
  BomNotMutableError,
  InvalidComponentQuantityError,
  ComponentItemInactiveError,
  AmbiguousEffectivityRuleError,
} from "../lib/errors.generated";
import { baseDraftBom, baseActiveBom, baseBomLine, baseItem } from "../testing/fixtures";
import { mockItemQueries } from "../testing/moduleMocks";
import { run } from "./updateBillOfMaterial";

describe("updateBillOfMaterial", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["manufacturing: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 mock = createKyselyMock<Namespace["main-db"]>();
    const updatedBom = {
      ...baseDraftBom,
      bomType: "PHANTOM" as const,
    };

    mock.enqueueResults(
      [baseDraftBom],
      [updatedBom],
      [],
      [{ ...baseBomLine, requiredQuantity: 3.0 }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, validInput, ctx, mockItemQueries([{ ...baseItem, id: "item-2" }])),
    );

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

    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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseActiveBom]);

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

    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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseDraftBom]);

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

    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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseDraftBom]);

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

    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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseDraftBom],
      // conflicting active BOM with same default selection
      [
        {
          ...baseActiveBom,
          defaultSelection: true,
          effectivityStartDate: null,
          effectivityEndDate: null,
        },
      ],
    );

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

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