import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { ContactPersonNotFoundError, InvalidStateTransitionError } from "../lib/errors.generated";
import { baseActiveContact, baseInactiveContact } from "../testing/fixtures";
import { run } from "./deactivateContactPerson";

describe("deactivateContactPerson", () => {
  it("deactivates an active contact person", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [{ ...baseActiveContact, isPrimary: false }],
      [{ ...baseActiveContact, isPrimary: false, status: "INACTIVE" }],
    );

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

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

  it("removes primary designation when deactivating primary contact", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseActiveContact],
      [{ ...baseActiveContact, isPrimary: false, status: "INACTIVE" }],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.contact.isPrimary).toBe(false);
      expect(result.value.contact.status).toBe("INACTIVE");
    }
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({ isPrimary: false, status: "INACTIVE" }),
    );
  });

  it("returns error when contact 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(ContactPersonNotFoundError);
    }
  });

  it("returns error when contact is already inactive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseInactiveContact]);

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

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