package com.yaoyuan.jiscuss.service.impl;

import com.yaoyuan.jiscuss.common.Node;
import com.yaoyuan.jiscuss.common.PostCommonUtil;
import com.yaoyuan.jiscuss.entity.Post;
import com.yaoyuan.jiscuss.entity.custom.PostCustom;
import com.yaoyuan.jiscuss.repository.DiscussionsRepository;
import com.yaoyuan.jiscuss.repository.PostsRepository;
import com.yaoyuan.jiscuss.repository.UsersRepository;
import com.yaoyuan.jiscuss.service.IPostsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class PostsServiceImpl implements IPostsService {
    
    @Autowired
    private PostsRepository postsRepository;

    @Autowired
    private DiscussionsRepository discussionsRepository;

    @Autowired
    private UsersRepository usersRepository;

    @Transactional(readOnly = true)
    @Override
    public List<Post> getAllList() {
        return postsRepository.findAll();
    }

    @Transactional(readOnly = true)
    @Override
    public List<Post> findOneBy(Integer id) {
        List<Post> posts = postsRepository.findOneBy(id);
        return posts;
    }

    @Transactional(readOnly = true)
    @Override
    public Post findOneByid(Integer id) {
        Post post = new Post();
        post.setId(id);
        Example<Post> example = Example.of(post);
        Optional<Post> postRes = postsRepository.findOne(example);
        return postRes.get();
    }

    @Transactional(readOnly = true)
    @Override
    public List findPostCustomById(Integer id, String sort) {
        // Choose sort order for top-level posts
        List<Map<String, Object>> firstposts = switch (sort == null ? "newest" : sort) {
            case "oldest" -> postsRepository.findAllByDIdAndparentIdNullOldest(id);
            case "hot"    -> postsRepository.findAllByDIdAndparentIdNullHot(id);
            default       -> postsRepository.findAllByDIdAndparentIdNullNewest(id); // newest (root only, create_time desc)
        };
        List<PostCustom> firstpostCustomList = PostCommonUtil.getNewPostsObjMap(firstposts);

        //查询id为1且parentId不为null的评论
        List<Map<String, Object>> thenposts = postsRepository.findAllByDIdAndparentIdNotNull(id);
        List<PostCustom> thenpostCustomList = PostCommonUtil.getNewPostsObjMap(thenposts);

        //新建一个Node集合。
        ArrayList<Node> nodes = new ArrayList<>();
        //将第一层评论都添加都Node集合中
        for (PostCustom post : firstpostCustomList) {
            Node node = new Node();
            BeanUtils.copyProperties(post, node);
            nodes.add(node);
        }
        //将回复添加到对应的位置
        List list = Node.addAllNode(nodes, thenpostCustomList);
        //打印回复链表
        Node.show(list);

        return list;
    }

    @Transactional
    @Override
    public Post insert(Post post) {
        // Auto-assign floor number within the same transaction to ensure consistency
        if (post.getDiscussionId() != null) {
            int nextNumber = postsRepository.findMaxNumberByDiscussionId(post.getDiscussionId()) + 1;
            post.setNumber(nextNumber);
        }
        Post saved = postsRepository.save(post);

        // Maintain discussion comment count and last activity
        if (post.getDiscussionId() != null) {
            discussionsRepository.incrementCommentCount(post.getDiscussionId(), post.getCreateId(), new Date());
        }
        // Maintain user comment count
        if (post.getCreateId() != null) {
            usersRepository.incrementCommentCount(post.getCreateId());
        }
        return saved;
    }
}
