package com.yaoyuan.jiscuss.controller;

import com.yaoyuan.jiscuss.entity.Discussion;
import com.yaoyuan.jiscuss.entity.Post;
import com.yaoyuan.jiscuss.entity.User;
import com.yaoyuan.jiscuss.entity.UserInfo;
import com.yaoyuan.jiscuss.repository.DiscussionsRepository;
import com.yaoyuan.jiscuss.repository.LikeCollectRepository;
import com.yaoyuan.jiscuss.repository.PostsRepository;
import com.yaoyuan.jiscuss.service.IMessageService;
import com.yaoyuan.jiscuss.service.INotificationService;
import com.yaoyuan.jiscuss.service.IUsersService;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Chuyaoyuan
 */
@Controller
public class UserPageController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(UserPageController.class);

    @Autowired
    private IUsersService usersService;

    @Autowired
    private DiscussionsRepository discussionsRepository;

    @Autowired
    private PostsRepository postsRepository;

    @Autowired
    private LikeCollectRepository likeCollectRepository;

    @Autowired
    private IMessageService messageService;

    @Autowired
    private INotificationService notificationService;

    /**
     * 用户个人主页
     */
    @RequestMapping("/user")
    public String user(@RequestParam(defaultValue = "discussion") String type,
                       HttpServletRequest request, ModelMap map) {

        UserInfo currentUser = getUserInfo(request);
        if (currentUser == null) return "redirect:/login";

        User userEntity = usersService.findOne(currentUser.getId());
        long liveDiscCount = discussionsRepository.countByStartUserId(currentUser.getId());
        long liveReplyCount = postsRepository.countByCreateId(currentUser.getId());
        map.put("username", currentUser.getUsername());
        map.put("userEntity", userEntity);
        map.put("liveDiscCount", liveDiscCount);
        map.put("liveReplyCount", liveReplyCount);
        map.put("type", type);
        map.put("unreadMsgCount", messageService.countUnread(currentUser.getId()));
        map.put("unreadNotifCount", notificationService.countUnread(currentUser.getId()));

        if ("discussion".equals(type)) {
            Page<Discussion> discussions = discussionsRepository.findByStartUserIdOrderByStartTimeDesc(
                    currentUser.getId(), PageRequest.of(0, 20));
            map.put("discussions", discussions.getContent());
        } else if ("reply".equals(type)) {
            Page<Post> posts = postsRepository.findByCreateIdOrderByCreateTimeDesc(
                    currentUser.getId(), PageRequest.of(0, 20));
            map.put("posts", posts.getContent());
            // Attach discussion titles
            List<String> discTitles = new ArrayList<>();
            for (Post p : posts.getContent()) {
                if (p.getDiscussionId() != null) {
                    Discussion d = discussionsRepository.findById(p.getDiscussionId()).orElse(null);
                    discTitles.add(d != null ? d.getTitle() : "");
                } else {
                    discTitles.add("");
                }
            }
            map.put("discTitles", discTitles);
        } else if ("like".equals(type)) {
            List<Integer> likedIds = likeCollectRepository.findLikedDiscussionIdsByUser(currentUser.getId());
            List<Discussion> liked = new ArrayList<>();
            for (Integer id : likedIds) {
                Discussion d = discussionsRepository.findById(id).orElse(null);
                if (d != null) liked.add(d);
            }
            map.put("likedDiscussions", liked);
        }

        return "user";
    }
}
