import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { ContactPersonNotFoundError, InvalidStateTransitionError } from "../lib/errors.generated";
import { baseActiveContact, baseInactiveContact } from "../testing/fixtures";
import { run } from "./reactivateContactPerson";

describe("reactivateContactPerson", () => {
  it("reactivates an inactive contact person", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseInactiveContact);
    spies.update.mockReturnValue({
      ...baseInactiveContact,
      status: "ACTIVE",
    });

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.contact.status).toBe("ACTIVE");
    }
  });

  it("returns error when contact not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "nonexistent" });

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

  it("returns error when contact is already active", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveContact);

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

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