import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import {
  DuplicateAssignmentError,
  ItemNotFoundError,
  NodeNotFoundError,
} from "../lib/errors.generated";
import { baseActiveItem, baseAssignment, baseChildNode } from "../testing/fixtures";
import { run } from "./assignItemToTaxonomy";

describe("assignItemToTaxonomy", () => {
  it("returns error when item does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // Item not found

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

  it("returns error when node does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseActiveItem) // Item exists
      .mockReturnValueOnce(undefined); // Node not found

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

  it("returns error when assignment already exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseActiveItem) // Item exists
      .mockReturnValueOnce(baseChildNode) // Node exists
      .mockReturnValueOnce(baseAssignment); // Assignment exists

    const result = await run(db, { itemId: baseActiveItem.id, taxonomyNodeId: baseChildNode.id });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(DuplicateAssignmentError);
    }
  });

  it("creates assignment successfully", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdAssignment = {
      ...baseAssignment,
      id: "new-assignment-id",
      itemId: baseActiveItem.id,
      taxonomyNodeId: baseChildNode.id,
    };
    spies.select
      .mockReturnValueOnce(baseActiveItem) // Item exists
      .mockReturnValueOnce(baseChildNode) // Node exists
      .mockReturnValueOnce(undefined); // No existing assignment
    spies.insert.mockReturnValue(createdAssignment);

    const result = await run(db, { itemId: baseActiveItem.id, taxonomyNodeId: baseChildNode.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.assignment.itemId).toBe(baseActiveItem.id);
      expect(result.value.assignment.taxonomyNodeId).toBe(baseChildNode.id);
    }
    expect(spies.insert).toHaveBeenCalled();
  });
});
