import * as Contacts from 'expo-contacts';

import { PersonContactAllResponse } from '../api/APIS/OrganizationUnit/types';

type NewContact = {
  id?: string;
  firstName?: string;
  lastName?: string;
  displayName?: string;
  phone?: PersonContactAllResponse;
  email?: PersonContactAllResponse;
};

export const addContact = async (person: NewContact) => {
  const { status } = await Contacts.requestPermissionsAsync();
  if (status === 'granted') {
    const newContact = {
      id: person.id || '',
      name: person.displayName || '',
      contactType: Contacts.ContactTypes.Person,
      [Contacts.Fields.FirstName]: person.firstName || '',
      [Contacts.Fields.LastName]: person.lastName || '',
      [Contacts.Fields.PhoneNumbers]: [
        {
          number: person.phone?.value || '',
          isPrimary: true,
        },
      ],
      [Contacts.Fields.Emails]: [
        {
          email: person.email?.value || '',
          isPrimary: true,
        },
      ],
    };
    Contacts.presentFormAsync(null, newContact);
  }
};
