package com.eactive.eai.rms.onl.apim.portalInquiry;

import com.eactive.apim.portal.qna.entity.Inquiry;
import com.eactive.apim.portal.qna.entity.InquiryComment;
import com.eactive.eai.rms.data.entity.onl.apim.portalinquiry.PortalInquiryCommentRepository;
import com.eactive.eai.rms.data.entity.onl.apim.portalinquiry.PortalInquiryCommentService;
import com.eactive.eai.rms.data.entity.onl.apim.portalinquiry.PortalInquiryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * RESPONDED 상태 문의글 중 아래 조건에 해당하는 경우 CLOSED로 변경한다.
 * - 조건 A: 활성 댓글이 없고 답변완료일(responseDate)로부터 N일 경과
 * - 조건 B: 마지막 관리자 댓글(adminYn=Y) 이후 N일간 포탈사용자(adminYn=N) 댓글 없음
 */
@Service
@Transactional(transactionManager = "transactionManagerForEMS")
@Slf4j
@RequiredArgsConstructor
public class PortalInquiryClosingService {

    private static final String RESPONDED = "RESPONDED";
    private static final String CLOSED = "CLOSED";

    private final PortalInquiryService portalInquiryService;
    private final PortalInquiryCommentService portalInquiryCommentService;
    private final PortalInquiryCommentRepository inquiryCommentRepository;

    public int closeExpiredInquiries(int closingDays) {
        LocalDateTime threshold = LocalDateTime.now().minusDays(closingDays);
        List<Inquiry> respondedInquiries = portalInquiryService.findByInquiryStatus(RESPONDED);

        int closedCount = 0;
        for (Inquiry inquiry : respondedInquiries) {
            if (shouldClose(inquiry, threshold)) {
                inquiry.setInquiryStatus(CLOSED);
                portalInquiryService.save(inquiry);
                closedCount++;
                log.info("문의글 CLOSED 처리: id={}", inquiry.getId());
            }
        }
        log.info("InquiryCommentClosingService: 총 {}건 CLOSED 처리 (기준={}일)", closedCount, closingDays);
        return closedCount;
    }

    private boolean shouldClose(Inquiry inquiry, LocalDateTime threshold) {
        long activeCommentCount = portalInquiryCommentService.countActiveByInquiryId(inquiry.getId());

        // 댓글 없음 → 답변완료일 기준 N일 경과 여부만 확인
        if (activeCommentCount == 0) {
            LocalDateTime responseDate = inquiry.getResponseDate();
            return responseDate != null && !responseDate.isAfter(threshold);
        }

        // 가장 최근 활성 댓글 확인
        Optional<InquiryComment> lastComment = inquiryCommentRepository
                .findTopByInquiry_IdAndDelYnOrderByCreatedDateDesc(inquiry.getId(), "N");

        if (!lastComment.isPresent()) {
            return false;
        }

        // 포탈사용자(adminYn != 'Y')가 마지막 댓글 작성자 → CLOSED 불가
        if (!"Y".equals(lastComment.get().getAdminYn())) {
            return false;
        }

        // 관리자가 마지막 댓글 작성자 → N일 경과 여부 확인
        LocalDateTime lastAdminDate = lastComment.get().getCreatedDate();
        return lastAdminDate != null && !lastAdminDate.isAfter(threshold);
    }
}
