import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { CategoryNotFoundError, MissingRequiredFieldError } from "../lib/errors.generated";
import { baseRootCategory } from "../testing/fixtures";
import { run } from "./updateProductCategory";

describe("updateProductCategory", () => {
  it("should return CategoryNotFoundError when category does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);
    const input = { id: "non-existent", name: "New Name" };
    const result = await mock.withTx((trx) => run(trx, input));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CategoryNotFoundError);
    }
  });

  it("should return MissingRequiredFieldError when no fields are provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseRootCategory]);
    const input = { id: baseRootCategory.id };
    const result = await mock.withTx((trx) => run(trx, input));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
  });

  it("should pass custom fields through to update", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedCategory = { ...baseRootCategory, priority: 1, updatedAt: new Date() };
    mock.enqueueResults([baseRootCategory], [updatedCategory]);

    const result = await mock.withTx((trx) => run(trx, { id: baseRootCategory.id, priority: 1 }));
    expect(result.ok).toBe(true);
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({
        priority: 1,
      }),
    );
  });

  it("should update category name successfully", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedCategory = { ...baseRootCategory, name: "Apparel", updatedAt: new Date() };
    mock.enqueueResults([baseRootCategory], [updatedCategory]);

    const input = {
      id: baseRootCategory.id,
      name: "Apparel",
    };
    const result = await mock.withTx((trx) => run(trx, input));
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.category.name).toBe("Apparel");
    }
  });

  it("should look up category by code and update name", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedCategory = { ...baseRootCategory, name: "Apparel", updatedAt: new Date() };
    mock.enqueueResults([baseRootCategory], [updatedCategory]);

    const result = await mock.withTx((trx) =>
      run(trx, { code: baseRootCategory.code, name: "Apparel" }),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.category.name).toBe("Apparel");
    }
  });
});
