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

describe("deleteContactPerson", () => {
  it("deletes a non-primary active contact person", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseNonPrimaryContact]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.id).toBe(baseNonPrimaryContact.id);
    }
    expect(mock.deletes).toHaveLength(1);
  });

  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 not active", 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(ContactNotActiveError);
    }
  });

  it("returns error when contact is primary", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveContact]); // isPrimary: true

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

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