package cn.axzo.msg.center.message.service.impl.person;

import cn.axzo.basics.profiles.api.UserProfileServiceApi;
import cn.axzo.basics.profiles.common.enums.IdentityType;
import cn.axzo.basics.profiles.dto.basic.IdentityProfileDto;
import cn.axzo.basics.profiles.dto.basic.PersonProfileDto;
import cn.axzo.msg.center.common.utils.BizAssertions;
import cn.azxo.framework.common.model.CommonResponse;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;

/**
 * @author yanglin
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PersonService {

    private final UserProfileServiceApi userProfileServiceApi;

    public PersonIdInfo getPersonIdsByIdentities(Collection<Long> identityIds) {
        log.info("start - querying person ids by identity ids: {}", JSON.toJSONString(identityIds));
        ArrayList<Long> uniqueIdentityIds = new ArrayList<>(new HashSet<>(identityIds));
        CommonResponse<List<IdentityProfileDto>> resp = userProfileServiceApi.getIdentitiesByIdSet(
                uniqueIdentityIds, IdentityType.NOT_SUPPORT.getCode());
        log.info("end - querying person ids by identity ids, request={}, response={}",
                JSON.toJSONString(identityIds), JSON.toJSONString(resp));
        BizAssertions.assertResponse(resp);
        return new PersonIdInfo(resp.getData());
    }

    public Optional<Long> getPersonIdByPhone(String phone) {
        if (StringUtils.isBlank(phone))
            return Optional.empty();
        CommonResponse<PersonProfileDto> profileResp = userProfileServiceApi
                .getUnionPersonProfile(null, phone);
        PersonProfileDto data = profileResp.getData();
        return Optional.ofNullable(data == null ? null : data.getId());
    }

    public Optional<String> getPhoneByPersonId(Long personId) {
        if (personId == null)
            return Optional.empty();
        CommonResponse<PersonProfileDto> profileResp = userProfileServiceApi
                .getPersonProfile(personId);
        PersonProfileDto data = profileResp.getData();
        return Optional.ofNullable(data == null ? null : data.getPhone());
    }
}