import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { baseCategoryAssignment } from "../testing/fixtures";
import { AssignmentNotFoundError } from "../lib/errors.generated";
import type { RemoveProductFromCategoryInput } from "./removeProductFromCategory";
import { run } from "./removeProductFromCategory";

describe("removeProductFromCategory", () => {
  it("should return AssignmentNotFoundError when assignment does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // getProductCategoryAssignment -> null
    spies.select.mockReturnValueOnce(undefined);
    const input: RemoveProductFromCategoryInput = {
      productId: "non-existent",
      categoryId: "non-existent",
    };
    const result = await run(db, input);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(AssignmentNotFoundError);
    }
  });

  it("should remove assignment successfully", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // getProductCategoryAssignment -> found
    spies.select.mockReturnValueOnce(baseCategoryAssignment);
    // delete executes
    spies.delete.mockReturnValueOnce(undefined);

    const input: RemoveProductFromCategoryInput = {
      productId: baseCategoryAssignment.productId,
      categoryId: baseCategoryAssignment.categoryId,
    };
    const result = await run(db, input);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.id).toBe(baseCategoryAssignment.id);
    }
  });
});
