import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 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 not ACTIVE", 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(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStateTransitionError);
    }
  });

  it("returns error when item is already 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(InvalidStateTransitionError);
    }
  });

  it("deactivates an ACTIVE item", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivatedItem = { ...baseActiveItem, status: "INACTIVE" };
    mock.enqueueResults([baseActiveItem], [deactivatedItem]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.item.status).toBe("INACTIVE");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });
});
