import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  ContactPersonNotFoundError,
  InvalidFirstNameError,
  InvalidLastNameError,
  InvalidEmailFormatError,
  MissingCommunicationChannelError,
} from "../lib/errors.generated";
import { baseActiveContact, baseNonPrimaryContact } from "../testing/fixtures";
import { run } from "./updateContactPerson";

describe("updateContactPerson", () => {
  it("updates contact person details", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveContact], [{ ...baseActiveContact, firstName: "Updated" }]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.contact.firstName).toBe("Updated");
    }
  });

  it("returns error when contact not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(trx, {
        id: "nonexistent",
        firstName: "Updated",
      }),
    );

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

  it("returns error when first name is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveContact]);

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

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

  it("returns error when first name is whitespace-only", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveContact]);

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

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

  it("returns error when last name is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveContact]);

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

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

  it("returns error when last name is whitespace-only", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveContact]);

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

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

  it("returns error when email format is invalid", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveContact]);

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

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

  it("returns error when update would leave no communication channel", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    // baseNonPrimaryContact has phone but no email
    mock.enqueueResults([baseNonPrimaryContact]);

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

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

  it("returns error when whitespace-only phone would leave no communication channel", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    // Contact with only phone (no email)
    mock.enqueueResults([baseNonPrimaryContact]);

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

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

  it("does not change organization association", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveContact], [{ ...baseActiveContact, firstName: "Updated" }]);

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

    expect(result.ok).toBe(true);
    expect(mock.updates[0].updateValues()).toEqual(
      expect.not.objectContaining({ partnerId: expect.anything() as unknown }),
    );
  });

  it("preserves primary contact designation", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveContact], [{ ...baseActiveContact, firstName: "Updated" }]);

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

    expect(result.ok).toBe(true);
    expect(mock.updates[0].updateValues()).toEqual(
      expect.not.objectContaining({ isPrimary: expect.anything() as unknown }),
    );
  });
});
