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 "./deactivateItem";

describe("deactivateItem", () => {
  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 ACTIVE", 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("returns error when item is already 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(InvalidStateTransitionError);
    }
  });

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

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

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

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

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

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