package cokr.xit.ens.modules.common.ctgy.mblpage.service;

import cokr.xit.ens.core.aop.EnsResponseVO;
import cokr.xit.ens.core.exception.EnsException;
import cokr.xit.ens.core.exception.code.EnsErrCd;
import cokr.xit.ens.core.utils.MapDeserailizer;
import cokr.xit.ens.modules.common.code.PostSeCd;
import cokr.xit.ens.modules.common.ctgy.mblpage.domain.SendDetailMblPage;
import cokr.xit.ens.modules.common.ctgy.mblpage.domain.repository.SendDetailMblPageRepository;
import cokr.xit.ens.modules.common.ctgy.mblpage.model.SendDetailMblPageDTO;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class SendDetailMblPageService {

    private final SendDetailMblPageRepository sendDetailMblPageRepository;

    private Gson gson = new GsonBuilder().registerTypeAdapter(Map.class, new MapDeserailizer()).serializeNulls().create();

    /**
     * 접수 서비스
     *
     * @param dto
     * @return
     */
    public EnsResponseVO create(SendDetailMblPageDTO dto) {

        final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<SendDetailMblPageDTO>> list = validator.validate(dto);
        if (list.size() > 0) {
            return EnsResponseVO.errRsltBuilder()
                    .errCode(EnsErrCd.ERR402)
                    .errMsg("유효하지 않은 요청값 입니다.")
                    .resultInfo(list.stream()
                            .map(row -> String.format("%s [ %s ]", row.getMessageTemplate(), row.getPropertyPath()))
                            .collect(Collectors.toList()))
                    .build();
        }
        try {
            PostSeCd.valueOf(dto.getPostSe());
        } catch (IllegalArgumentException e) {
            throw new EnsException(EnsErrCd.ERR403, String.format("우편구분 \"%s\" 값이 유효하지 않습니다. %s", dto.getPostSe(), Arrays.stream(PostSeCd.values()).map(revnSeCd -> revnSeCd.getCode()).collect(Collectors.toList()).toString()));
        }



        SendDetailMblPage sendDetailMblPage = SendDetailMblPage.builder()
                .postSe(dto.getPostSe())
                .sendDetailId(dto.getSendDetailId())
                .details(gson.toJson(dto.getDocument()))
                .build();
        sendDetailMblPageRepository.save(sendDetailMblPage);


        return EnsResponseVO.<SendDetailMblPage>okBuilder().resultInfo(sendDetailMblPage).build();
    }


}
