import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { ProductNotFoundError, CategoryNotFoundError } from "../lib/errors.generated";
import { baseActiveProduct, baseChildCategory, baseCategoryAssignment } from "../testing/fixtures";
import type { AssignProductToCategoryInput } from "./assignProductToCategory";
import { run } from "./assignProductToCategory";

describe("assignProductToCategory", () => {
  it("should return ProductNotFoundError when product does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);
    const input: AssignProductToCategoryInput = {
      productId: "non-existent",
      categoryId: baseChildCategory.id,
    };
    const result = await mock.withTx((trx) => run(trx, input));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ProductNotFoundError);
    }
  });

  it("should return CategoryNotFoundError when category does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveProduct], []);
    const input: AssignProductToCategoryInput = {
      productId: baseActiveProduct.id,
      categoryId: "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 create assignment successfully", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const newAssignment = {
      ...baseCategoryAssignment,
      id: "new-assign-id",
      productId: baseActiveProduct.id,
      categoryId: baseChildCategory.id,
    };
    mock.enqueueResults([baseActiveProduct], [baseChildCategory], [], [newAssignment]);

    const input: AssignProductToCategoryInput = {
      productId: baseActiveProduct.id,
      categoryId: baseChildCategory.id,
    };
    const result = await mock.withTx((trx) => run(trx, input));
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productCategoryAssignment).toEqual(newAssignment);
    }
  });

  it("should return existing assignment when already assigned (idempotent)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveProduct], [baseChildCategory], [baseCategoryAssignment]);

    const input: AssignProductToCategoryInput = {
      productId: baseActiveProduct.id,
      categoryId: baseChildCategory.id,
    };
    const result = await mock.withTx((trx) => run(trx, input));
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productCategoryAssignment).toEqual(baseCategoryAssignment);
    }
    expect(mock.inserts).toHaveLength(0);
  });
});
