package com.jeesharp.business.modules.ai.application;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.ai.convert.AiChatMessageConvert;
import com.jeesharp.business.modules.ai.dto.AiChatMessageSaveDTO;
import com.jeesharp.business.modules.ai.entity.AiChatMessage;
import com.jeesharp.business.modules.ai.service.AiChatMessageService;
import com.jeesharp.business.modules.ai.service.AiChatSessionService;
import com.jeesharp.business.modules.ai.vo.AiChatMessageInfoVO;
import com.jeesharp.business.modules.ai.vo.AiChatMessageListVO;
import com.jeesharp.business.modules.ai.vo.AiChatMessageQueryVO;
import com.jeesharp.business.modules.member.service.MemberService;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * AI 客服消息应用服务：后台消息查询、维护及会话/会员展示信息编排。
 *
 * @author jeesharp
 * @since 2026-06-04
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class AiChatMessageApplicationService {

    private final AiChatMessageService aiChatMessageService;
    private final AiChatSessionService aiChatSessionService;
    private final MemberService memberService;

    public AiChatMessageInfoVO get(String id) {
        AiChatMessage entity = aiChatMessageService.get(id);
        if (entity == null) {
            return null;
        }
        AiChatMessageInfoVO vo = AiChatMessageConvert.INSTANCE.toInfoVO(entity);
        enrichInfoDisplay(vo);
        return vo;
    }

    public PageRespVO<AiChatMessageListVO> findPage(Page<AiChatMessage> page, AiChatMessageQueryVO query) {
        AiChatMessageQueryVO prepared = prepareQuery(query);
        if (prepared == null) {
            return emptyPage(page);
        }
        Page<AiChatMessage> result = aiChatMessageService.findPage(page, prepared);
        PageRespVO<AiChatMessageListVO> pageVo = AiChatMessageConvert.INSTANCE.toPageRespVO(result);
        enrichListDisplay(pageVo.getRecords());
        return pageVo;
    }

    @Transactional(readOnly = false)
    public void save(AiChatMessageSaveDTO dto) {
        AiChatMessage entity = AiChatMessageConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            aiChatMessageService.createMessage(entity);
            return;
        }
        aiChatMessageService.updateMessage(entity);
    }

    @Transactional(readOnly = false)
    public void delete(String ids) {
        aiChatMessageService.batchDelete(StrUtil.splitTrim(ids, ','));
    }

    /**
     * 管理端名称类筛选：会话标题/编码、会员关键词 → 主键 IN。
     */
    private AiChatMessageQueryVO prepareQuery(AiChatMessageQueryVO query) {
        AiChatMessageQueryVO q = query != null ? query : new AiChatMessageQueryVO();
        if (StrUtil.isNotBlank(q.getMemberKeyword())) {
            List<String> memberIds = memberService.findIdsByKeyword(q.getMemberKeyword().trim());
            q.setMemberKeyword(null);
            if (CollUtil.isEmpty(memberIds)) {
                return null;
            }
            q.setMemberIdIn(memberIds);
        }
        if (StrUtil.isNotBlank(q.getSessionTitle())) {
            List<String> sessionIds = aiChatSessionService.findIdsByTitleOrCodeLike(q.getSessionTitle().trim());
            q.setSessionTitle(null);
            if (CollUtil.isEmpty(sessionIds)) {
                return null;
            }
            q.setSessionIdIn(sessionIds);
        }
        return q;
    }

    private void enrichListDisplay(List<AiChatMessageListVO> rows) {
        if (CollUtil.isEmpty(rows)) {
            return;
        }
        memberService.enrichMemberDisplay(rows);
        List<String> sessionIds = rows.stream()
            .map(AiChatMessageListVO::getSessionId)
            .filter(StrUtil::isNotBlank)
            .distinct()
            .toList();
        Map<String, String> sessionLabelMap = aiChatSessionService.mapSessionLabelByIds(sessionIds);
        for (AiChatMessageListVO row : rows) {
            if (StrUtil.isNotBlank(row.getSessionId())) {
                row.setSessionTitle(sessionLabelMap.get(row.getSessionId()));
            }
        }
    }

    private void enrichInfoDisplay(AiChatMessageInfoVO vo) {
        if (vo == null) {
            return;
        }
        memberService.enrichMemberDisplay(vo);
        if (StrUtil.isNotBlank(vo.getSessionId())) {
            Map<String, String> labelMap = aiChatSessionService.mapSessionLabelByIds(List.of(vo.getSessionId()));
            vo.setSessionTitle(labelMap.get(vo.getSessionId()));
        }
    }

    private static PageRespVO<AiChatMessageListVO> emptyPage(Page<AiChatMessage> page) {
        PageRespVO<AiChatMessageListVO> empty = new PageRespVO<>();
        empty.setRecords(Collections.emptyList());
        empty.setTotal(0L);
        empty.setPageNo(page != null ? page.getPageNo() : 1L);
        empty.setPageSize(page != null ? page.getPageSize() : 10L);
        return empty;
    }
}
