package com.test.bijihoudaun.controller;

import com.test.bijihoudaun.annotation.RequireCaptcha;
import com.test.bijihoudaun.bo.UpdatePasswordBo;
import cn.hutool.core.util.ObjectUtil;
import com.test.bijihoudaun.common.response.R;
import com.test.bijihoudaun.entity.User;
import com.test.bijihoudaun.entity.UserVO;
import com.test.bijihoudaun.service.RegistrationCodeService;
import com.test.bijihoudaun.service.SystemSettingService;
import com.test.bijihoudaun.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

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

@Tag(name = "用户接口")
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private SystemSettingService systemSettingService;

    @Autowired
    private RegistrationCodeService registrationCodeService;

    @Operation(summary = "用户注册")
    @Parameters({
            @Parameter(name = "username", description = "用户名",required = true),
            @Parameter(name = "password", description = "密码",required = true),
            @Parameter(name = "email", description = "邮箱",required = true),
            @Parameter(name = "registrationCode", description = "注册码", required = true)
    })
    @PostMapping("/register")
    public R<UserVO> register(String username, String password, String email, String registrationCode){
        if (!systemSettingService.isRegistrationEnabled()) {
            return R.fail("注册功能已关闭");
        }
        if (!registrationCodeService.validateCode(registrationCode)) {
            return R.fail("无效或已过期的注册码");
        }
        User user = userService.register(username, password, email);
        // 修复：添加空值检查
        if (user == null) {
            return R.fail("注册失败，请稍后重试");
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setId(String.valueOf(user.getId()));
        return R.success(userVO);
    }

    @Operation(summary = "用户登录")
    @Parameters({
            @Parameter(name = "username", description = "用户名",required = true),
            @Parameter(name = "password", description = "密码",required = true)
    })
    @PostMapping("/login")
    public R<Map<String, Object>> login(String username, String password){
        try {
            String token = userService.login(username, password);
            User user = userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>().eq("username", username));
            
            // 修复：添加空值检查
            if (user == null) {
                return R.fail("用户不存在");
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", String.valueOf(user.getId()));
            userInfo.put("username", user.getUsername());
            userInfo.put("email", user.getEmail());
            String role = user.getRole();
            userInfo.put("role", (role != null && !role.isEmpty()) ? role : "USER");
            result.put("userInfo", userInfo);
            
            return R.success(result);
        } catch (BadCredentialsException e) {
            return R.fail("用户名或密码错误");
        }
    }

    @Operation(summary = "删除当前登录的用户")
    @RequireCaptcha("删除账号")
    @DeleteMapping("/deleteUser")
    public R<String> deleteUser(){
        // 修复：添加类型检查
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!(principal instanceof UserDetails)) {
            return R.fail("无法获取用户信息");
        }
        UserDetails userDetails = (UserDetails) principal;
        String username = userDetails.getUsername();
        User user = userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>().eq("username", username));

        if (ObjectUtil.isNull(user)) {
            return R.fail("无法获取用户信息，删除失败");
        }

        userService.deleteUser(user.getId());
        return R.success("用户删除成功");
    }

    @Operation(summary = "验证Token有效性")
    @PostMapping("/validate-token")
    public R<String> validateToken() {
        return R.success("Token is valid");
    }

    @Operation(summary = "更新用户密码")
    @RequireCaptcha("修改密码")
    @PutMapping("/password")
    public R<String> updatePassword(@RequestBody UpdatePasswordBo updatePasswordBo) {
        // 修复：添加类型检查
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!(principal instanceof UserDetails)) {
            return R.fail("无法获取用户信息");
        }
        UserDetails userDetails = (UserDetails) principal;
        String username = userDetails.getUsername();
        User user = userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>().eq("username", username));
        
        // 修复：添加空值检查
        if (ObjectUtil.isNull(user)) {
            return R.fail("用户不存在");
        }
        
        userService.updatePassword(user.getId(), updatePasswordBo);
        return R.success("密码更新成功");
    }
}
