package com.example.demo.controller;

import com.example.demo.service.UserService;
import com.example.demo.util.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员控制器
 * 提供管理员功能，包括积分管理
 */
@RestController
@RequestMapping("/api/admin")
public class AdminController {

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

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 给用户增加积分
     */
    @PostMapping("/add-points")
    public ResponseEntity<Map<String, Object>> addPoints(
            @RequestParam String username,
            @RequestParam Integer points,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证管理员权限
            String adminUsername = extractUsernameFromToken(token);
            if (adminUsername == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 增加用户积分
            userService.addPoints(username, points);
            
            response.put("success", true);
            response.put("message", "积分增加成功");
            response.put("username", username);
            response.put("points", points);
            
            logger.info("管理员 {} 为用户 {} 增加了 {} 积分", adminUsername, username, points);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("增加积分失败", e);
            response.put("success", false);
            response.put("message", "增加积分失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 重置用户积分为默认值
     */
    @PostMapping("/reset-points")
    public ResponseEntity<Map<String, Object>> resetPoints(
            @RequestParam String username,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证管理员权限
            String adminUsername = extractUsernameFromToken(token);
            if (adminUsername == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 重置用户积分为100
            userService.setPoints(username, 100);
            
            response.put("success", true);
            response.put("message", "积分重置成功");
            response.put("username", username);
            response.put("points", 100);
            
            logger.info("管理员 {} 重置用户 {} 的积分为 100", adminUsername, username);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("重置积分失败", e);
            response.put("success", false);
            response.put("message", "重置积分失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 从Token中提取用户名
     */
    private String extractUsernameFromToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return null;
            }
            
            String actualToken = jwtUtils.extractTokenFromHeader(token);
            if (actualToken == null) {
                return null;
            }
            
            String username = jwtUtils.getUsernameFromToken(actualToken);
            if (username != null && !jwtUtils.isTokenExpired(actualToken)) {
                return username;
            }
            
            return null;
        } catch (Exception e) {
            logger.error("解析token失败", e);
            return null;
        }
    }
}

