import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

  it("returns error when node has children", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseRootNode], [baseChildNode]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseLeafNode], [], [baseAssignment]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseLeafNode], [], []);

    const result = await mock.withTx((trx) => run(trx, { id: baseLeafNode.id }));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.success).toBe(true);
    }
    expect(mock.deletes.length).toBeGreaterThan(0);
  });
});
