package cn.teammodel.service.impl;

import cn.hutool.core.lang.UUID;
import cn.teammodel.common.ErrorCode;
import cn.teammodel.common.PK;
import cn.teammodel.config.exception.ServiceException;
import cn.teammodel.model.dto.ai.UpdateSessionDto;
import cn.teammodel.model.entity.ai.ChatSession;
import cn.teammodel.model.entity.ai.ChatSession.Message;
import cn.teammodel.repository.ChatSessionRepository;
import cn.teammodel.service.ChatSessionService;
import cn.teammodel.utils.RepositoryUtil;
import com.azure.cosmos.models.CosmosPatchOperations;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author winter
 * @create 2023-12-19 15:31
 */
@Service
@Slf4j
public class ChatSessionServiceImpl implements ChatSessionService {
    @Resource
    private ChatSessionRepository chatSessionRepository;

    @Override
    public String createSession(String userId, String name) {
        // 初始化欢迎语
        Message message = Message.of("", "你好" + name + " ,我是你的私人 AI 助手小豆,你可以问我任何包括但不仅限于教育的问题,我会尽力为您解答!","SparkMax");
        List<Message> history = Collections.singletonList(message);
        ChatSession chatSession = new ChatSession();
        chatSession.setId(UUID.randomUUID().toString());
        chatSession.setCode(PK.CHAT_SESSION);
        chatSession.setTitle("新对话");
        chatSession.setUserId(userId);
        chatSession.setCreateTime(Instant.now().toEpochMilli());
        chatSession.setUpdateTime(Instant.now().toEpochMilli());
        chatSession.setHistory(history);
        return chatSessionRepository.save(chatSession).getId();
    }

    @Override
    public List<ChatSession> listMySession(String userId) {

        List<ChatSession> sessions = chatSessionRepository.findByUserId(userId);
        // 按更新时间排序
        if (ObjectUtils.isNotEmpty(sessions)) {
            sessions = sessions.stream().sorted(Comparator.comparing(ChatSession::getUpdateTime)).collect(Collectors.toList());
        }
        return sessions;
    }

    @Override
    public ChatSession updateSession(UpdateSessionDto updateSessionDto, String userId) {
        String id = updateSessionDto.getId();
        String title = updateSessionDto.getTitle();

        ChatSession session = RepositoryUtil.findOne(chatSessionRepository.findBySessionId(id), "");
        if (!session.getUserId().equals(userId)) {
            throw new ServiceException(ErrorCode.NO_AUTH_ERROR);
        }
        CosmosPatchOperations options = CosmosPatchOperations.create()
                .replace("/title", title);
        chatSessionRepository.save(id, PK.of(PK.CHAT_SESSION), ChatSession.class, options);
        return null;
    }

    @Override
    public void deleteSession(String id, String userId) {
        ChatSession session = RepositoryUtil.findOne(chatSessionRepository.findBySessionId(id), "该会话不存在");
        // 鉴权
        if (!session.getUserId().equals(userId)) {
            throw new ServiceException(ErrorCode.NO_AUTH_ERROR);
        }
        chatSessionRepository.deleteById(id, PK.of(PK.CHAT_SESSION));
    }

    @Override
    public List<Message> listHistory(String sessionId, String userId) {
        ChatSession session = chatSessionRepository.findChatSessionByIdAndCode(sessionId, PK.CHAT_SESSION);
        if (!userId.equals(session.getUserId())) {
            throw new ServiceException(ErrorCode.NO_AUTH_ERROR);
        }
        return session.getHistory();
    }
}
