def apply()

in handlers/identity-backfill/src/main/scala/com/gu/identityBackfill/salesforce/GetSFContactSyncCheckFields.scala [59:100]


  def apply(
      standardRecordType: RecordTypeId,
  )(
      contactSyncCheckFields: List[GetSFContactSyncCheckFields.ContactSyncCheckFields],
  ): Either[String, SFContactId] = {

    def isStandardContact(fields: ContactSyncCheckFields) = fields.RecordTypeId.contains(standardRecordType.value)

    contactSyncCheckFields.filter(isStandardContact) match {
      case fields :: Nil => {
        val email = fields.Email.getOrElse("")
        val emailIsValid = email.length > 3 && email.contains("@")
        val country = fields.OtherCountry.getOrElse("").trim
        val countryIsValid = country.nonEmpty && CountryGroup.byOptimisticCountryNameOrCode(country).isDefined
        if (fields.FirstName.trim.isEmpty) {
          Left(s"Contact ${fields.Id} is not syncable - does not have a first name")
        } else if (fields.LastName.trim.isEmpty) {
          Left(s"Contact ${fields.Id} is not syncable - does not have a last name")
        } else if (!emailIsValid) {
          Left(s"Contact ${fields.Id} is not syncable - does not have a valid email address: $email")
        } else if (!countryIsValid) {
          Left(s"Contact ${fields.Id} is not syncable - does not have a valid country: $country")
        } else {
          Right(SFContactId(fields.Id))
        }
      }
      case _ :: _ :: Nil =>
        Left(
          s"There are more than one syncable SF Contacts within this SF Account: ${contactSyncCheckFields.map(_.Id)}",
        )
      case Nil if contactSyncCheckFields.nonEmpty =>
        Left(
          s"There are no syncable SF Contacts within the customer's account: ${contactSyncCheckFields.map(_.Id).mkString(", ")}",
        )
      case Nil if contactSyncCheckFields.isEmpty =>
        Left(s"There are no SF Contacts within the customer's account")
      case _ =>
        Left(
          s"Syncable SF Contact did not meet validation: ${contactSyncCheckFields.map(_.Id)}",
        ) // should never happen!
    }
  }