package com.yaoyuan.jiscuss.controller.api;

import com.yaoyuan.jiscuss.controller.BaseController;
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.response.ApiResponse;
import com.yaoyuan.jiscuss.service.IMessageService;
import com.yaoyuan.jiscuss.service.INotificationService;
import com.yaoyuan.jiscuss.service.IUsersService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * REST API for private messages and notifications.
 */
@Tag(name = "Message API", description = "Private messages and notifications")
@RestController
@RequestMapping("/msg_api")
public class RestMsgController extends BaseController {

    @Autowired
    private IMessageService messageService;

    @Autowired
    private INotificationService notificationService;

    @Autowired
    private IUsersService usersService;

    // ─── Debug (TEMP) ─────────────────────────────────────────────────────

    /** Temp debug: returns raw message counts and inbox list for current user. */
    @GetMapping("/debug/inbox")
    public ApiResponse<Map<String, Object>> debugInbox(HttpServletRequest request) {
        UserInfo user = getUserInfo(request);
        if (user == null) return ApiResponse.fail(401, "请先登录");
        long unread = messageService.countUnread(user.getId());
        List<Message> inbox = messageService.getInbox(user.getId());
        return ApiResponse.ok(Map.of(
                "userId", user.getId(),
                "username", user.getUsername(),
                "unreadCount", unread,
                "inboxSize", inbox.size(),
                "inbox", inbox
        ));
    }

    // ─── User card (public — accessible to any authenticated user) ────────

    /** Returns basic user info for the hover card (discussionsCount, commentsCount). */
    @Operation(summary = "Get user card info")
    @GetMapping("/user-card/{id}")
    public ApiResponse<Map<String, Object>> getUserCard(@PathVariable Integer id, HttpServletRequest request) {
        UserInfo currentUser = getUserInfo(request);
        if (currentUser == null) return ApiResponse.fail(401, "请先登录");
        User user = usersService.findOne(id);
        if (user == null) return ApiResponse.fail(404, "用户不存在");
        return ApiResponse.ok(Map.of(
                "id", user.getId(),
                "username", user.getUsername() != null ? user.getUsername() : "",
                "discussionsCount", user.getDiscussionsCount() != null ? user.getDiscussionsCount() : 0,
                "commentsCount", user.getCommentsCount() != null ? user.getCommentsCount() : 0
        ));
    }

    // ─── Notifications ────────────────────────────────────────────────────

    @Operation(summary = "Get unread notification + message counts")
    @GetMapping("/unread-counts")
    public ApiResponse<Map<String, Long>> unreadCounts(HttpServletRequest request) {
        UserInfo user = getUserInfo(request);
        if (user == null) return ApiResponse.ok(Map.of("notifications", 0L, "messages", 0L));
        return ApiResponse.ok(Map.of(
                "notifications", notificationService.countUnread(user.getId()),
                "messages", messageService.countUnread(user.getId())
        ));
    }

    @Operation(summary = "Mark a notification as read")
    @PostMapping("/notifications/{id}/read")
    public ApiResponse<Void> markNotifRead(@PathVariable Integer id, HttpServletRequest request) {
        UserInfo user = getUserInfo(request);
        if (user == null) return ApiResponse.fail(401, "请先登录");
        notificationService.markOneRead(id, user.getId());
        return ApiResponse.ok(null);
    }

    @Operation(summary = "Mark all notifications as read")
    @PostMapping("/notifications/read-all")
    public ApiResponse<Void> markAllNotifRead(HttpServletRequest request) {
        UserInfo user = getUserInfo(request);
        if (user == null) return ApiResponse.fail(401, "请先登录");
        notificationService.markAllRead(user.getId());
        return ApiResponse.ok(null);
    }

    // ─── Messages ─────────────────────────────────────────────────────────

    @Operation(summary = "Send a private message")
    @PostMapping("/messages/send")
    public ApiResponse<Message> sendMessage(
            @RequestParam Integer receiverId,
            @RequestParam String content,
            HttpServletRequest request) {
        UserInfo user = getUserInfo(request);
        if (user == null) return ApiResponse.fail(401, "请先登录");
        if (user.getId().equals(receiverId)) return ApiResponse.fail(400, "不能给自己发消息");
        if (content == null || content.isBlank()) return ApiResponse.fail(400, "消息内容不能为空");
        Message msg = messageService.send(user.getId(), receiverId, content.trim());
        return ApiResponse.ok(msg);
    }

    @Operation(summary = "Get conversation with another user")
    @GetMapping("/messages/conversation/{otherId}")
    public ApiResponse<List<Message>> getConversation(@PathVariable Integer otherId, HttpServletRequest request) {
        UserInfo user = getUserInfo(request);
        if (user == null) return ApiResponse.fail(401, "请先登录");
        messageService.markConversationRead(user.getId(), otherId);
        return ApiResponse.ok(messageService.getConversation(user.getId(), otherId));
    }
}
