import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { baseRootCategory } from "../testing/fixtures";
import { CategoryNotFoundError, MissingRequiredFieldError } from "../lib/errors.generated";
import { run } from "./updateProductCategory";

describe("updateProductCategory", () => {
  it("should return CategoryNotFoundError when category does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);
    const input = { id: "non-existent", name: "New Name" };
    const result = await run(db, 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseRootCategory);
    const input = { id: baseRootCategory.id };
    const result = await run(db, input);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
  });

  it("should pass custom fields through to update", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseRootCategory);
    const updatedCategory = { ...baseRootCategory, priority: 1, updatedAt: new Date() };
    spies.update.mockReturnValueOnce(updatedCategory);

    const result = await run(db, { id: baseRootCategory.id, priority: 1 });
    expect(result.ok).toBe(true);
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({
        priority: 1,
      }),
    );
  });

  it("should update category name successfully", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseRootCategory);
    const updatedCategory = { ...baseRootCategory, name: "Apparel", updatedAt: new Date() };
    spies.update.mockReturnValueOnce(updatedCategory);

    const input = {
      id: baseRootCategory.id,
      name: "Apparel",
    };
    const result = await run(db, 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseRootCategory);
    const updatedCategory = { ...baseRootCategory, name: "Apparel", updatedAt: new Date() };
    spies.update.mockReturnValueOnce(updatedCategory);

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