import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { InvalidStateTransitionError, PartnerNotFoundError } from "../lib/errors.generated";
import { baseActivePartner, baseDraftPartner, baseInactivePartner } from "../testing/fixtures";
import { run } from "./reactivatePartner";

describe("reactivatePartner", () => {
  it("reactivates an INACTIVE partner", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const reactivatedPartner = { ...baseInactivePartner, status: "ACTIVE" };
    spies.select.mockReturnValueOnce(baseInactivePartner);
    spies.update.mockReturnValue(reactivatedPartner);

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

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

  it("returns error when partner not found", 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(PartnerNotFoundError);
    }
  });

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

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

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStateTransitionError);
    }
  });

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

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

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStateTransitionError);
    }
  });
});
