package com.mosquito.project.controller;

import com.mosquito.project.dto.ApiResponse;
import com.mosquito.project.persistence.entity.NotificationEntity;
import com.mosquito.project.permission.RequirePermission;
import com.mosquito.project.service.NotificationService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

/**
 * 通知管理控制器
 * 已持久化到数据库
 */
@RestController
@RequestMapping("/api/v1")
public class NotificationController {

    private final NotificationService notificationService;

    public NotificationController(NotificationService notificationService) {
        this.notificationService = notificationService;
    }

    /**
     * 从请求属性中获取当前用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        Object userIdObj = request.getAttribute("userId");
        if (userIdObj instanceof Long) {
            return (Long) userIdObj;
        } else if (userIdObj instanceof Integer) {
            return ((Integer) userIdObj).longValue();
        } else if (userIdObj instanceof String) {
            try {
                return Long.parseLong((String) userIdObj);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 获取当前用户通知列表
     */
    @GetMapping("/notifications")
    @RequirePermission("notification.index.view.ALL")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getNotifications(
            @RequestParam(required = false, defaultValue = "0") Integer page,
            @RequestParam(required = false, defaultValue = "20") Integer size,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Boolean isRead,
            @RequestParam(required = false) String keyword,
            HttpServletRequest request) {

        Long currentUserId = getCurrentUserId(request);
        if (currentUserId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录或token无效"));
        }

        Map<String, Object> result = notificationService.getNotifications(currentUserId, page, size, type, isRead, keyword);
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 获取当前用户未读通知数量
     */
    @GetMapping("/notifications/unread-count")
    @RequirePermission("notification.index.view.ALL")
    public ResponseEntity<ApiResponse<Long>> getUnreadCount(HttpServletRequest request) {
        Long currentUserId = getCurrentUserId(request);
        if (currentUserId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录或token无效"));
        }

        long count = notificationService.getUnreadCount(currentUserId);
        return ResponseEntity.ok(ApiResponse.success(count));
    }

    /**
     * 创建通知
     */
    @PostMapping("/notifications")
    @RequirePermission("notification.index.manage.ALL")
    public ResponseEntity<ApiResponse<NotificationEntity>> createNotification(
            @RequestBody Map<String, Object> requestBody,
            HttpServletRequest httpRequest) {

        Long currentUserId = getCurrentUserId(httpRequest);
        if (currentUserId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录或token无效"));
        }

        String title = (String) requestBody.get("title");
        String content = (String) requestBody.get("content");
        String type = (String) requestBody.getOrDefault("type", "SYSTEM");

        if (title == null || title.isBlank()) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "标题不能为空"));
        }

        NotificationEntity notification = new NotificationEntity();
        notification.setTitle(title);
        notification.setContent(content);
        notification.setType(type);
        notification.setUserId(currentUserId);
        notification.setCreatedBy(currentUserId);
        notification.setIsRead(false);

        NotificationEntity saved = notificationService.createNotification(notification);
        return ResponseEntity.ok(ApiResponse.success(saved, "通知创建成功"));
    }

    /**
     * 标记通知为已读
     */
    @PostMapping("/notifications/{id}/read")
    @RequirePermission("notification.index.manage.ALL")
    public ResponseEntity<ApiResponse<Void>> markNotificationRead(
            @PathVariable Long id,
            HttpServletRequest request) {

        Long currentUserId = getCurrentUserId(request);
        if (currentUserId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录或token无效"));
        }

        boolean success = notificationService.markAsRead(id, currentUserId);
        if (success) {
            return ResponseEntity.ok(ApiResponse.success(null, "标记已读成功"));
        }
        return ResponseEntity.ok(ApiResponse.error(404, "通知不存在"));
    }

    /**
     * 标记所有通知为已读
     */
    @PostMapping("/notifications/read-all")
    @RequirePermission("notification.index.manage.ALL")
    public ResponseEntity<ApiResponse<Integer>> markAllNotificationsRead(HttpServletRequest request) {
        Long currentUserId = getCurrentUserId(request);
        if (currentUserId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录或token无效"));
        }

        int count = notificationService.markAllAsRead(currentUserId);
        return ResponseEntity.ok(ApiResponse.success(count, "已标记" + count + "条通知为已读"));
    }

    /**
     * 批量标记为已读
     */
    @PostMapping("/notifications/batch-read")
    @RequirePermission("notification.index.manage.ALL")
    public ResponseEntity<ApiResponse<Integer>> batchMarkAsRead(
            @RequestBody List<Long> notificationIds,
            HttpServletRequest request) {

        Long currentUserId = getCurrentUserId(request);
        if (currentUserId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录或token无效"));
        }

        int count = notificationService.batchMarkAsRead(notificationIds, currentUserId);
        return ResponseEntity.ok(ApiResponse.success(count, "已标记" + count + "条通知为已读"));
    }

    /**
     * 删除通知
     */
    @DeleteMapping("/notifications/{id}")
    @RequirePermission("notification.index.manage.ALL")
    public ResponseEntity<ApiResponse<Void>> deleteNotification(
            @PathVariable Long id,
            HttpServletRequest request) {

        Long currentUserId = getCurrentUserId(request);
        if (currentUserId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error(401, "未登录或token无效"));
        }

        boolean success = notificationService.deleteNotification(id, currentUserId);
        if (success) {
            return ResponseEntity.ok(ApiResponse.success(null, "删除成功"));
        }
        return ResponseEntity.ok(ApiResponse.error(404, "通知不存在"));
    }
}
