package com.yaoyuan.jiscuss.controller;

import com.yaoyuan.jiscuss.dto.InboxItem;
import com.yaoyuan.jiscuss.entity.Message;
import com.yaoyuan.jiscuss.entity.Notification;
import com.yaoyuan.jiscuss.entity.User;
import com.yaoyuan.jiscuss.entity.UserInfo;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

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

/**
 * @author Chuyaoyuan
 * 站内私信与通知控制器
 */
@Controller
public class UserMsgController extends BaseController {

    @Autowired
    private IMessageService messageService;

    @Autowired
    private INotificationService notificationService;

    @Autowired
    private IUsersService usersService;

    /** 收件箱：对话列表 */
    @GetMapping("/messages")
    public String inbox(HttpServletRequest request, ModelMap map) {
        UserInfo user = getUserInfo(request);
        if (user == null) return "redirect:/login";

        List<Message> inboxList = messageService.getInbox(user.getId());

        List<InboxItem> items = new ArrayList<>();
        for (Message msg : inboxList) {
            Integer otherId = msg.getSenderId().equals(user.getId()) ? msg.getReceiverId() : msg.getSenderId();
            User other = usersService.findOne(otherId);
            String rawName = (other != null) ? other.getUsername() : null;
            String otherName = (rawName != null && !rawName.isBlank()) ? rawName : "用户" + otherId;
            boolean hasUnread = !Boolean.TRUE.equals(msg.getIsRead()) && msg.getReceiverId().equals(user.getId());
            items.add(new InboxItem(otherId, otherName, msg.getContent(), msg.getCreateTime(), hasUnread));
        }

        map.put("username", user.getUsername());
        map.put("currentUserId", user.getId());
        map.put("inboxItems", items);
        map.put("unreadMsgCount", messageService.countUnread(user.getId()));
        map.put("unreadNotifCount", notificationService.countUnread(user.getId()));
        return "messages";
    }

    /** 对话详情页 */
    @GetMapping("/messages/{otherId}")
    public String conversation(@PathVariable Integer otherId, HttpServletRequest request, ModelMap map) {
        UserInfo user = getUserInfo(request);
        if (user == null) return "redirect:/login";

        messageService.markConversationRead(user.getId(), otherId);

        List<Message> messages = messageService.getConversation(user.getId(), otherId);
        User other = usersService.findOne(otherId);

        map.put("username", user.getUsername());
        map.put("currentUserId", user.getId());
        map.put("otherId", otherId);
        map.put("otherUsername", other != null ? other.getUsername() : "用户" + otherId);
        map.put("messages", messages);
        map.put("unreadMsgCount", messageService.countUnread(user.getId()));
        map.put("unreadNotifCount", notificationService.countUnread(user.getId()));
        return "conversation";
    }

    /** 通知列表页 */
    @GetMapping("/notifications")
    public String notifications(@RequestParam(defaultValue = "0") int page,
                                HttpServletRequest request, ModelMap map) {
        UserInfo user = getUserInfo(request);
        if (user == null) return "redirect:/login";

        notificationService.markAllRead(user.getId());
        Page<Notification> notifs = notificationService.listByUser(user.getId(), page, 20);

        List<String> fromUsernames = new ArrayList<>();
        for (Notification n : notifs.getContent()) {
            if (n.getFromUserId() != null) {
                User from = usersService.findOne(n.getFromUserId());
                fromUsernames.add(from != null ? from.getUsername() : "用户" + n.getFromUserId());
            } else {
                fromUsernames.add("系统");
            }
        }

        map.put("username", user.getUsername());
        map.put("notifications", notifs.getContent());
        map.put("fromUsernames", fromUsernames);
        map.put("totalPages", notifs.getTotalPages());
        map.put("currentPage", page);
        map.put("unreadMsgCount", messageService.countUnread(user.getId()));
        map.put("unreadNotifCount", 0L);
        return "notifications";
    }
}
