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,
  BomNotActivatableError,
  ComponentLineRequiredError,
  ComponentItemInactiveError,
  CircularBomReferenceError,
  EffectivityConflictError,
} from "../lib/errors.generated";
import { baseDraftBom, baseActiveBom, baseBomLine, baseItem } from "../testing/fixtures";
import { mockItemQueries } from "../testing/moduleMocks";
import { run } from "./activateBillOfMaterial";

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

  it("activates a valid draft BOM", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activatedBom = { ...baseDraftBom, status: "ACTIVE" as const };

    mock.enqueueResults([baseDraftBom], [baseBomLine], [], [activatedBom]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.billOfMaterial.status).toBe("ACTIVE");
    }
    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, 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, { id: "bom-2" }, ctx, mockItemQueries([])));

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

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

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

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

  it("returns error when a component item is inactive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseDraftBom], [baseBomLine]);

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

    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 mock = createKyselyMock<Namespace["main-db"]>();
    const bomWithSubassembly = {
      ...baseDraftBom,
    };
    const subassemblyLine = {
      ...baseBomLine,
      isSubassembly: true,
      itemId: "item-sub",
    };

    mock.enqueueResults(
      [bomWithSubassembly],
      [subassemblyLine],
      [
        {
          ...baseDraftBom,
          id: "child-bom",
          parentItemId: "item-sub",
        },
      ],
      [{ ...baseBomLine, itemId: "item-1" }],
    );

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

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

    mock.enqueueResults(
      [baseDraftBom],
      [baseBomLine],
      [
        {
          ...baseActiveBom,
          defaultSelection: true,
          effectivityStartDate: null,
          effectivityEndDate: null,
        },
      ],
    );

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

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