import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveContact);
    spies.update.mockReturnValue({
      ...baseActiveContact,
      firstName: "Updated",
    });

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveContact);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveContact);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveContact);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveContact);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveContact);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    // baseNonPrimaryContact has phone but no email
    spies.select.mockReturnValueOnce(baseNonPrimaryContact);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    // Contact with only phone (no email)
    spies.select.mockReturnValueOnce(baseNonPrimaryContact);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveContact);
    spies.update.mockReturnValue({
      ...baseActiveContact,
      firstName: "Updated",
    });

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

    expect(result.ok).toBe(true);
    expect(spies.set).toHaveBeenCalledWith(
      expect.not.objectContaining({ partnerId: expect.anything() as unknown }),
    );
  });

  it("preserves primary contact designation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveContact);
    spies.update.mockReturnValue({
      ...baseActiveContact,
      firstName: "Updated",
    });

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

    expect(result.ok).toBe(true);
    expect(spies.set).toHaveBeenCalledWith(
      expect.not.objectContaining({ isPrimary: expect.anything() as unknown }),
    );
  });
});
