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 {
  InvalidUomError,
  MissingRequiredFieldError,
  NoFieldsToUpdateError,
  ProductNotFoundError,
  UomLockedError,
} from "../lib/errors.generated";
import { baseActiveProduct, baseDraftProduct } from "../testing/fixtures";
import { run } from "./updateProduct";

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

  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 product not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);
    const result = await mock.withTx((trx) =>
      run(trx, { id: "nonexistent", name: "New Name" }, ctx, primitivesQueries),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ProductNotFoundError);
    }
  });

  it("returns error when no fields provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseDraftProduct }]);
    const result = await mock.withTx((trx) =>
      run(trx, { id: "product-1" }, ctx, primitivesQueries),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(NoFieldsToUpdateError);
    }
  });

  it("returns error when name is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseDraftProduct }]);
    const result = await mock.withTx((trx) =>
      run(trx, { id: "product-1", name: "" }, ctx, primitivesQueries),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
  });

  it("returns error when UoM locked on non-DRAFT", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseActiveProduct }]);
    const result = await mock.withTx((trx) =>
      run(trx, { id: "product-2", unitId: "unit-pcs" }, ctx, primitivesQueries),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(UomLockedError);
    }
  });

  it("returns error when UoM is invalid", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseDraftProduct }]);
    const result = await mock.withTx((trx) =>
      run(trx, { id: "product-1", unitId: "unit-invalid" }, ctx, primitivesQueries),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidUomError);
    }
  });

  it("updates description successfully", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...baseDraftProduct, description: "A new description" };
    mock.enqueueResults([{ ...baseDraftProduct }], [updated]);
    const result = await mock.withTx((trx) =>
      run(trx, { id: "product-1", description: "A new description" }, ctx, primitivesQueries),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.product.description).toBe("A new description");
    }
  });

  it("updates UoM successfully on DRAFT product", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...baseDraftProduct, unitId: "unit-pcs" };
    mock.enqueueResults([{ ...baseDraftProduct }], [updated]);
    const result = await mock.withTx((trx) =>
      run(trx, { id: "product-1", unitId: "unit-pcs" }, ctx, primitivesQueries),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.product.unitId).toBe("unit-pcs");
    }
  });

  it("updates name successfully", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...baseDraftProduct, name: "Updated Name" };
    mock.enqueueResults([{ ...baseDraftProduct }], [updated]);
    const result = await mock.withTx((trx) =>
      run(trx, { id: "product-1", name: "Updated Name" }, ctx, primitivesQueries),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.product.name).toBe("Updated Name");
    }
  });

  it("looks up product by code and updates name", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...baseDraftProduct, name: "Updated Name" };
    mock.enqueueResults([{ ...baseDraftProduct }], [updated]);
    const result = await mock.withTx((trx) =>
      run(trx, { code: baseDraftProduct.code, name: "Updated Name" }, ctx, primitivesQueries),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.product.name).toBe("Updated Name");
    }
  });

  it("passes custom fields through", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...baseDraftProduct, customField1: "value1" };
    mock.enqueueResults([{ ...baseDraftProduct }], [updated]);
    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: "product-1", name: "Updated", customField1: "value1" },
        ctx,
        primitivesQueries,
      ),
    );
    expect(result.ok).toBe(true);
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({
        customField1: "value1",
      }),
    );
  });
});
