import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import {
  NodeHasAssignmentsError,
  NodeHasChildrenError,
  NodeNotFoundError,
} from "../lib/errors.generated";
import { baseAssignment, baseChildNode, baseLeafNode, baseRootNode } from "../testing/fixtures";
import { run } from "./deleteTaxonomyNode";

describe("deleteTaxonomyNode", () => {
  it("returns error when node does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(undefined);

    const result = await run(db, { id: "nonexistent" });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(NodeNotFoundError);
    }
  });

  it("returns error when node has children", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseRootNode) // getTaxonomyNode
      .mockReturnValueOnce([baseChildNode]); // getTaxonomyNodeChildren (execute returns array)

    const result = await run(db, { id: baseRootNode.id });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(NodeHasChildrenError);
    }
  });

  it("returns error when node has item assignments", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseLeafNode) // getTaxonomyNode
      .mockReturnValueOnce([]) // getTaxonomyNodeChildren (no children)
      .mockReturnValueOnce([baseAssignment]); // getTaxonomyNodeAssignments (has assignment)

    const result = await run(db, { id: baseLeafNode.id });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(NodeHasAssignmentsError);
    }
  });

  it("deletes a leaf node with no assignments", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseLeafNode) // getTaxonomyNode
      .mockReturnValueOnce([]) // getTaxonomyNodeChildren (no children)
      .mockReturnValueOnce([]); // getTaxonomyNodeAssignments (no assignments)
    spies.delete.mockReturnValue(undefined);

    const result = await run(db, { id: baseLeafNode.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.success).toBe(true);
    }
    expect(spies.delete).toHaveBeenCalled();
  });
});
