package com.arms.api.poc.service;

import com.arms.api.poc.model.dto.PocDTO;
import com.arms.api.poc.model.entity.PocEntity;
import com.arms.api.poc.model.vo.PocVO;
import com.arms.egovframework.javaservice.esframework.model.dto.esquery.SearchDocDTO;
import com.arms.egovframework.javaservice.esframework.model.dto.esquery.SortDTO;
import com.arms.egovframework.javaservice.esframework.model.vo.DocumentResultWrapper;
import com.arms.egovframework.javaservice.esframework.repository.common.EsCommonRepositoryWrapper;
import com.arms.egovframework.javaservice.esframework.esquery.SimpleQuery;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@AllArgsConstructor
public class PocServiceImpl implements PocService {

    private final EsCommonRepositoryWrapper<PocEntity> esCommonRepositoryWrapper;

    @Override
    public String createPoc(PocDTO pocDTO) {

        PocEntity pocEntity = pocDTO.toPocEntityWithCreate();

        // Full name 생성
        if (pocEntity.getC_poc_full_name() == null || pocEntity.getC_poc_full_name().isEmpty()) {
            String fullName = formatFullName(pocEntity);
            pocEntity.setC_poc_full_name(fullName);
        }

        PocEntity save = esCommonRepositoryWrapper.save(pocEntity);

        return save.getId();
    }

    @Override
    public PocEntity getPoc(String id) {

        PocEntity pocEntity = esCommonRepositoryWrapper.findDocById(id);

        if (pocEntity == null) {
            throw new IllegalArgumentException("POC를 찾을 수 없습니다: " + id);
        }

        return pocEntity;
    }

    @Override
    public PocVO getPocList(PocDTO pocDTO) {

        SimpleQuery<SearchDocDTO> query = SimpleQuery.search(pocDTO)
                .orderBy(SortDTO.builder().field("c_poc_inquiry_date").sortType("desc").build());

        DocumentResultWrapper<PocEntity> docsBySearchAfter = esCommonRepositoryWrapper.findDocsBySearchAfter(query);

        List<PocEntity> pocList = docsBySearchAfter.toDocs();
        Long totalCount = docsBySearchAfter.getTotalHits();

        log.info("POC list fetched: totalCount={}", totalCount);

        return PocVO.builder()
                .pocEntities(pocList)
                .totalHits(totalCount)
                .searchAfter(docsBySearchAfter.getLastSortValue())
                .build();
    }

    @Override
    public String updatePoc(PocDTO pocDTO) {

        PocEntity findPocEntity = esCommonRepositoryWrapper.findDocById(pocDTO.getId());

        if (findPocEntity == null) {
            throw new IllegalArgumentException("POC를 찾을 수 없습니다: " + pocDTO.getId());
        }

        PocEntity updateEntity = pocDTO.toPocEntityWithUpdate();
        findPocEntity.updatePocEntity(updateEntity);

        PocEntity save = esCommonRepositoryWrapper.save(findPocEntity);

        return save.getId();
    }

    @Override
    public String deletePoc(String id) {

        PocEntity pocEntity = esCommonRepositoryWrapper.findDocById(id);

        if (pocEntity == null) {
            throw new IllegalArgumentException("POC를 찾을 수 없습니다: " + id);
        }

        esCommonRepositoryWrapper.deleteById(id);

        return id;
    }

    private String formatFullName(PocEntity pocEntity) {
        String firstName = pocEntity.getC_poc_first_name() != null ? pocEntity.getC_poc_first_name() : "";
        String lastName = pocEntity.getC_poc_last_name() != null ? pocEntity.getC_poc_last_name() : "";
        String country = pocEntity.getC_poc_country() != null ? pocEntity.getC_poc_country() : "";

        // 성이 먼저 오는 국가들 (한국, 일본, 중국)
        if (country.equals("KR") || country.equals("JP") || country.equals("CN")) {
            return lastName + " " + firstName;
        } else {
            return firstName + " " + lastName;
        }
    }
}
