import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    const reactivatedPartner = { ...baseInactivePartner, status: "ACTIVE" };
    mock.enqueueResults([baseInactivePartner], [reactivatedPartner]);

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

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

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

  it("returns error when partner is DRAFT", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftPartner]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActivePartner]);

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

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