package com.arms.api.newsletter.service;

import com.arms.api.newsletter.model.dto.NewsletterDTO;
import com.arms.api.newsletter.model.entity.NewsletterEntity;
import com.arms.api.newsletter.model.vo.NewsletterVO;
import com.arms.egovframework.javaservice.esframework.esquery.SimpleQuery;
import com.arms.egovframework.javaservice.esframework.repository.common.EsCommonRepositoryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@AllArgsConstructor
public class NewsletterServiceImpl implements NewsletterService {

    private final EsCommonRepositoryWrapper<NewsletterEntity> esCommonRepositoryWrapper;

    @Override
    public NewsletterVO addNewsletter(NewsletterDTO newsletterDTO) {
        NewsletterEntity newsletterEntity = esCommonRepositoryWrapper.save(newsletterDTO.createEntity());
        return NewsletterVO.builder()
                .id(newsletterEntity.getId())
                .contents(newsletterEntity.getContents())
                .build();
    }

    @Override
    public NewsletterVO getNewsletter(String newsletterId) {
        NewsletterEntity newsletterEntity = esCommonRepositoryWrapper.findDocById(newsletterId);
        return NewsletterVO.builder()
                .id(newsletterEntity.getId())
                .contents(newsletterEntity.getContents())
                .build();
    }

    @Override
    public NewsletterVO updateNewsletter(NewsletterDTO newsletterDTO) {
        String newsletterId = newsletterDTO.getId();

        NewsletterEntity newsletterEntity = esCommonRepositoryWrapper.findDocById(newsletterId);
        if (newsletterEntity == null) {
            throw new IllegalArgumentException("뉴스레터가 조회되지 않습니다.");
        }

        newsletterEntity.updateNewsletterEntity(newsletterDTO.createEntity());

        NewsletterEntity savedEntity = esCommonRepositoryWrapper.save(newsletterEntity);

        return NewsletterVO.builder()
                .id(savedEntity.getId())
                .contents(savedEntity.getContents())
                .build();
    }

    @Override
    public NewsletterVO deleteNewsletter(String newsletterId) {
        NewsletterEntity newsletterEntity = esCommonRepositoryWrapper.findDocById(newsletterId);

        if (newsletterEntity == null) {
            throw new IllegalArgumentException("뉴스레터가 조회되지 않습니다.");
        }

        // 뉴스레터 한건 제거라서 현재는 필요없는 로직
        List<NewsletterEntity> docs = esCommonRepositoryWrapper.findHits(
                SimpleQuery.termQueryFilter("id", newsletterEntity.getId()))
                .toDocs();

        for (NewsletterEntity doc : docs) {
            esCommonRepositoryWrapper.deleteById(doc.getId());
        }

        return NewsletterVO.builder()
                .id(newsletterEntity.getId())
                .contents(newsletterEntity.getContents())
                .build();
    }

}
