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

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

  it("returns error when SKU already exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftItem); // SKU lookup finds existing

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(undefined) // SKU unique
      .mockReturnValueOnce(baseActiveItem); // Barcode lookup finds existing

    const result = await run(
      db,
      { 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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(undefined) // SKU unique
      .mockReturnValueOnce(undefined); // UoM lookup fails

    const result = await run(
      db,
      { 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 { db, spies } = createMockDb<Transaction>();
    const activeUnit = { id: "unit-kg", isActive: true };
    const createdItem = { ...baseDraftItem, id: "new-item-id", sku: "SKU-NEW" };

    spies.select
      .mockReturnValueOnce(undefined) // SKU unique
      .mockReturnValueOnce(activeUnit); // UoM valid
    spies.insert.mockReturnValue(createdItem);

    const result = await run(db, { 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(spies.insert).toHaveBeenCalled();
  });

  it("creates item in ACTIVE status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activeUnit = { id: "unit-kg", isActive: true };
    const createdItem = { ...baseActiveItem, id: "new-item-id", sku: "SKU-NEW" };

    spies.select
      .mockReturnValueOnce(undefined) // SKU unique
      .mockReturnValueOnce(activeUnit); // UoM valid
    spies.insert.mockReturnValue(createdItem);

    const result = await run(
      db,
      { 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(spies.insert).toHaveBeenCalled();
  });

  it("skips barcode uniqueness check when barcode is not provided", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activeUnit = { id: "unit-kg", isActive: true };
    const createdItem = { ...baseDraftItem, id: "new-item-id" };

    spies.select
      .mockReturnValueOnce(undefined) // SKU unique
      .mockReturnValueOnce(activeUnit); // UoM valid (no barcode check)
    spies.insert.mockReturnValue(createdItem);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.item).toBeDefined();
    }
    expect(spies.select).toHaveBeenCalledTimes(2); // Only SKU + UoM checks
  });

  it("passes custom fields through to insert", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activeUnit = { id: "unit-kg", isActive: true };
    const createdItem = { ...baseDraftItem, id: "new-item-id", priority: 5 };

    spies.select
      .mockReturnValueOnce(undefined) // SKU unique
      .mockReturnValueOnce(activeUnit); // UoM valid
    spies.insert.mockReturnValue(createdItem);

    await run(db, { sku: "SKU-NEW", name: "Widget", unitId: "unit-kg", priority: 5 }, ctx, {
      getUnit,
    });

    expect(spies.values).toHaveBeenNthCalledWith(1, expect.objectContaining({ priority: 5 }));
  });
});
