import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import { InvalidStateTransitionError, ItemNotFoundError } from "../lib/errors.generated";
import { baseActiveItem, baseDraftItem, baseInactiveItem } from "../testing/fixtures";
import { run } from "./reactivateItem";

describe("reactivateItem", () => {
  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 not INACTIVE", 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(InvalidStateTransitionError);
    }
  });

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

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

  it("reactivates an INACTIVE item", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const reactivatedItem = { ...baseInactiveItem, status: "ACTIVE" };
    spies.select.mockReturnValueOnce(baseInactiveItem);
    spies.update.mockReturnValue(reactivatedItem);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.item.status).toBe("ACTIVE");
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("reactivates from custom status when from is overridden", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const reactivatedItem = { ...baseDraftItem, status: "ACTIVE" };
    spies.select.mockReturnValueOnce(baseDraftItem);
    spies.update.mockReturnValue(reactivatedItem);

    const result = await run(db, { id: baseDraftItem.id, from: ["INACTIVE", "DRAFT"] });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.item.status).toBe("ACTIVE");
    }
  });
});
