import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  CategoryNotFoundError,
  HasChildrenError,
  HasAssignmentsError,
} from "../lib/errors.generated";
import { baseLeafCategory, baseChildCategory, baseCategoryAssignment } from "../testing/fixtures";
import type { DeleteProductCategoryInput } from "./deleteProductCategory";
import { run } from "./deleteProductCategory";

describe("deleteProductCategory", () => {
  it("should return CategoryNotFoundError when category does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);
    const input: DeleteProductCategoryInput = { id: "non-existent" };
    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 HasChildrenError when category has children", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChildCategory], [baseLeafCategory]);
    const input: DeleteProductCategoryInput = { id: baseChildCategory.id };
    const result = await mock.withTx((trx) => run(trx, input));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(HasChildrenError);
    }
  });

  it("should return HasAssignmentsError when category has assignments", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseLeafCategory], [], [baseCategoryAssignment]);
    const input: DeleteProductCategoryInput = { id: baseLeafCategory.id };
    const result = await mock.withTx((trx) => run(trx, input));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(HasAssignmentsError);
    }
  });

  it("should delete leaf category successfully", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseLeafCategory], [], []);

    const input: DeleteProductCategoryInput = { id: baseLeafCategory.id };
    const result = await mock.withTx((trx) => run(trx, input));
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.id).toBe(baseLeafCategory.id);
    }
  });
});
