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 {
  ParentItemNotFoundError,
  ParentItemNotManufacturedError,
  ComponentLineRequiredError,
  InvalidComponentQuantityError,
  ComponentItemInactiveError,
  BomVersionConflictError,
} from "../lib/errors.generated";
import { baseDraftBom, baseBomLine, baseItem } from "../testing/fixtures";
import { mockItemQueries } from "../testing/moduleMocks";
import { run } from "./createBillOfMaterial";

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

  const validInput = {
    parentItemId: "item-1",
    companyId: "company-1",
    siteId: null,
    bomType: "MANUFACTURE" as const,
    effectivityStartDate: null,
    effectivityEndDate: null,
    defaultSelection: true,
    revisionNumber: "V1",
    lines: [
      {
        itemId: "item-2",
        requiredQuantity: 2.0,
        unitOfMeasure: "EA",
        scrapAssumption: 5.0,
        isSubassembly: false,
      },
    ],
  };

  it("creates a draft BOM for an active manufactured item", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdBom = {
      ...baseDraftBom,
      id: "new-bom-id",
    };

    mock.enqueueResults([], [createdBom], [{ ...baseBomLine, billOfMaterialId: "new-bom-id" }]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.billOfMaterial.status).toBe("DRAFT");
      expect(result.value.billOfMaterial.id).toBe("new-bom-id");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("returns error when the parent item does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

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

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

  it("returns error when the parent item is not manufacturable", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(trx, validInput, ctx, mockItemQueries([{ ...baseItem, isManufacturable: false }])),
    );

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

  it("returns error when no component lines are provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { ...validInput, lines: [] },
        ctx,
        mockItemQueries([{ ...baseItem, isManufacturable: true }]),
      ),
    );

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

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

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

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

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

    const result = await mock.withTx((trx) =>
      run(trx, validInput, ctx, mockItemQueries([{ ...baseItem, isManufacturable: true }])),
    );

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

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

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

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

  it("returns error when the version identity already exists in scope", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseDraftBom]);

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

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

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        validInput,
        ctx,
        mockItemQueries([{ ...baseItem, status: "INACTIVE", isManufacturable: true }]),
      ),
    );

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