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

describe("deactivatePartner", () => {
  it("deactivates an ACTIVE partner", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivatedPartner = { ...baseActivePartner, status: "INACTIVE" };
    spies.select.mockReturnValueOnce(baseActivePartner);
    spies.update.mockReturnValue(deactivatedPartner);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.partner.status).toBe("INACTIVE");
    }
    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 INACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseInactivePartner);

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

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