import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { GetUnitInput } from "../../primitives/query/getUnit";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  DuplicateCodeError,
  InvalidUomError,
  MissingRequiredFieldError,
} from "../lib/errors.generated";
import { baseDraftProduct } from "../testing/fixtures";
import { run } from "./createProduct";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  const baseUnit = {
    id: "unit-pcs",
    symbol: "pcs",
    name: "Pieces",
    roundingPrecision: 0,
    isActive: true,
    createdAt: new Date("2024-01-01"),
    updatedAt: null,
    categoryId: "uom-cat-1",
    conversionFactor: 1,
  };

  const mockGetUnit = (_db: unknown, input: GetUnitInput) =>
    Promise.resolve({
      ok: true as const,
      value: {
        unit: "id" in input && input.id === "unit-pcs" ? baseUnit : null,
      },
    });
  const primitivesQueries = { getUnit: mockGetUnit };

  it("returns error when code is empty", async () => {
    const { db } = createMockDb<Transaction>();
    const result = await run(
      db,
      { code: "", name: "Test", unitId: "unit-pcs" },
      ctx,
      primitivesQueries,
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
  });

  it("returns error when name is empty", async () => {
    const { db } = createMockDb<Transaction>();
    const result = await run(
      db,
      { code: "PROD-1", name: "", unitId: "unit-pcs" },
      ctx,
      primitivesQueries,
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
  });

  it("returns error when code already exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // getProduct select returns existing product
    spies.select.mockReturnValueOnce(baseDraftProduct);
    const result = await run(
      db,
      { code: "CLASSIC-TSHIRT", name: "Another Shirt", unitId: "unit-pcs" },
      ctx,
      primitivesQueries,
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(DuplicateCodeError);
    }
  });

  it("returns error when UoM is invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // getProduct select returns no existing product
    spies.select.mockReturnValueOnce(undefined);
    const result = await run(
      db,
      { code: "PROD-1", name: "Test Product", unitId: "unit-invalid" },
      ctx,
      primitivesQueries,
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidUomError);
    }
  });

  it("creates product in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // getProduct select returns no existing product
    spies.select.mockReturnValueOnce(undefined);
    // insert returns the new product
    spies.insert.mockReturnValueOnce({ ...baseDraftProduct });
    const result = await run(
      db,
      { code: "CLASSIC-TSHIRT", name: "Classic T-Shirt", unitId: "unit-pcs" },
      ctx,
      primitivesQueries,
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.product).toEqual(baseDraftProduct);
    }
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({
        code: "CLASSIC-TSHIRT",
        name: "Classic T-Shirt",
        unitId: "unit-pcs",
        status: "DRAFT",
      }),
    );
  });

  it("passes custom fields through", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);
    spies.insert.mockReturnValueOnce({ ...baseDraftProduct, customField1: "value1" });
    const result = await run(
      db,
      {
        code: "CLASSIC-TSHIRT",
        name: "Classic T-Shirt",
        unitId: "unit-pcs",
        customField1: "value1",
      },
      ctx,
      primitivesQueries,
    );
    expect(result.ok).toBe(true);
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({
        customField1: "value1",
      }),
    );
  });
});
