import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { DeleteNonDraftError, ItemNotFoundError } from "../lib/errors.generated";
import { baseActiveItem, baseDraftItem, baseInactiveItem } from "../testing/fixtures";
import { run } from "./deleteItem";

describe("deleteItem", () => {
  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, { id: "nonexistent" }));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemNotFoundError);
    }
  });

  it("returns error when item is ACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveItem]);

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

  it("returns error when item is INACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseInactiveItem]);

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

  it("deletes a DRAFT item and removes taxonomy assignments", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftItem]);

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

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