import { type CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import { getUnit } from "../../primitives/query/getUnit.generated";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  DuplicateBarcodeError,
  DuplicateSkuError,
  UnitNotFoundError,
} from "../lib/errors.generated";
import { baseActiveItem, baseDraftItem } from "../testing/fixtures";
import { run } from "./createItem";

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

  it("returns error when SKU already exists", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftItem]); // SKU lookup finds existing

    const result = await mock.withTx((trx) =>
      run(trx, { sku: "SKU-001", name: "Widget", unitId: "unit-kg" }, ctx, { getUnit }),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(DuplicateSkuError);
    }
  });

  it("returns error when barcode already exists", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [], // SKU unique
      [baseActiveItem], // Barcode lookup finds existing
    );

    const result = await mock.withTx((trx) =>
      run(trx, { sku: "SKU-NEW", name: "Widget", barcode: "BAR-002", unitId: "unit-kg" }, ctx, {
        getUnit,
      }),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(DuplicateBarcodeError);
    }
  });

  it("returns error when UoM does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [], // SKU unique
      [], // UoM lookup fails
    );

    const result = await mock.withTx((trx) =>
      run(trx, { sku: "SKU-NEW", name: "Widget", unitId: "nonexistent-unit" }, ctx, { getUnit }),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(UnitNotFoundError);
    }
  });

  it("creates item in DRAFT status by default", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activeUnit = { id: "unit-kg", status: "ACTIVE" as const };
    const createdItem = { ...baseDraftItem, id: "new-item-id", sku: "SKU-NEW" };

    mock.enqueueResults(
      [], // SKU unique
      [activeUnit], // UoM valid
      [createdItem],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { sku: "SKU-NEW", name: "Widget", unitId: "unit-kg" }, ctx, { getUnit }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.item.sku).toBe("SKU-NEW");
      expect(result.value.item.status).toBe("DRAFT");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("creates item in ACTIVE status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activeUnit = { id: "unit-kg", status: "ACTIVE" as const };
    const createdItem = { ...baseActiveItem, id: "new-item-id", sku: "SKU-NEW" };

    mock.enqueueResults(
      [], // SKU unique
      [activeUnit], // UoM valid
      [createdItem],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { sku: "SKU-NEW", name: "New Widget", unitId: "unit-kg", status: "ACTIVE" }, ctx, {
        getUnit,
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.item.status).toBe("ACTIVE");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("skips barcode uniqueness check when barcode is not provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activeUnit = { id: "unit-kg", status: "ACTIVE" as const };
    const createdItem = { ...baseDraftItem, id: "new-item-id" };

    mock.enqueueResults(
      [], // SKU unique
      [activeUnit], // UoM valid (no barcode check)
      [createdItem],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { sku: "SKU-001", name: "Widget", unitId: "unit-kg" }, ctx, { getUnit }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.item).toBeDefined();
    }
    expect(mock.selects).toHaveLength(2); // Only SKU + UoM checks
  });

  it("passes custom fields through to insert", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activeUnit = { id: "unit-kg", status: "ACTIVE" as const };
    const createdItem = { ...baseDraftItem, id: "new-item-id", priority: 5 };

    mock.enqueueResults(
      [], // SKU unique
      [activeUnit], // UoM valid
      [createdItem],
    );

    await mock.withTx((trx) =>
      run(trx, { sku: "SKU-NEW", name: "Widget", unitId: "unit-kg", priority: 5 }, ctx, {
        getUnit,
      }),
    );

    expect(mock.inserts[0].insertValues()).toEqual(expect.objectContaining({ priority: 5 }));
  });
});
