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

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

  const baseUnit = {
    id: "unit-pcs",
    symbol: "pcs",
    name: "Pieces",
    roundingPrecision: 0,
    status: "ACTIVE" as const,
    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 mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftProduct]);
    const result = await mock.withTx((trx) =>
      run(
        trx,
        { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);
    const result = await mock.withTx((trx) =>
      run(
        trx,
        { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([], [{ ...baseDraftProduct }]);
    const result = await mock.withTx((trx) =>
      run(
        trx,
        { 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(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({
        code: "CLASSIC-TSHIRT",
        name: "Classic T-Shirt",
        unitId: "unit-pcs",
        status: "DRAFT",
      }),
    );
  });

  it("passes custom fields through", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([], [{ ...baseDraftProduct, customField1: "value1" }]);
    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          code: "CLASSIC-TSHIRT",
          name: "Classic T-Shirt",
          unitId: "unit-pcs",
          customField1: "value1",
        },
        ctx,
        primitivesQueries,
      ),
    );
    expect(result.ok).toBe(true);
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({
        customField1: "value1",
      }),
    );
  });
});
