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

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

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

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const createdAssignment = {
      ...baseAssignment,
      id: "new-assignment-id",
      itemId: baseActiveItem.id,
      taxonomyNodeId: baseChildNode.id,
    };
    mock.enqueueResults([baseActiveItem], [baseChildNode], [], [createdAssignment]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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(mock.inserts.length).toBeGreaterThan(0);
  });
});
