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 { baseNonPrimaryContact, baseInactiveContact } from "../testing/fixtures";
import { run } from "./setPrimaryContactPerson";

describe("setPrimaryContactPerson", () => {
  it("sets contact as primary", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseNonPrimaryContact],
      [],
      [{ ...baseNonPrimaryContact, isPrimary: true }],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.contact.isPrimary).toBe(true);
    }
  });

  it("unsets previous primary contact", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseNonPrimaryContact],
      [],
      [{ ...baseNonPrimaryContact, isPrimary: true }],
    );

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

    expect(result.ok).toBe(true);
    // Two update calls: one to unset previous primary, one to set new primary
    expect(mock.updates).toHaveLength(2);
  });

  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 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);
    }
  });
});
