import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { baseAssignment } from "../testing/fixtures";
import { run } from "./getItemTaxonomyAssignment";

describe("getItemTaxonomyAssignment", () => {
  it("returns assignment when found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAssignment]);

    const result = await run(mock.db, { itemId: "item-2", taxonomyNodeId: "node-2" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.assignment).toEqual(baseAssignment);
    }

    expect(mock.selects).toHaveLength(1);
    expect(mock.selects[0]?.parameters).toContain("item-2");
    expect(mock.selects[0]?.parameters).toContain("node-2");
    expect(mock.selects[0]?.sql).toMatch(/"itemId"/);
    expect(mock.selects[0]?.sql).toMatch(/"taxonomyNodeId"/);
  });

  it("returns null when assignment not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { itemId: "item-1", taxonomyNodeId: "node-1" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.assignment).toBeNull();
    }

    expect(mock.selects).toHaveLength(1);
    expect(mock.selects[0]?.parameters).toContain("item-1");
    expect(mock.selects[0]?.parameters).toContain("node-1");
    expect(mock.selects[0]?.sql).toMatch(/"itemId"/);
    expect(mock.selects[0]?.sql).toMatch(/"taxonomyNodeId"/);
  });
});
