import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(undefined);

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

  it("returns error when item is ACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveItem);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseInactiveItem);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftItem);
    spies.delete.mockReturnValue(undefined); // Assignments delete + item delete

    const result = await run(db, { id: baseDraftItem.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.success).toBe(true);
    }
    expect(spies.delete).toHaveBeenCalled();
  });
});
