package com.example.demo.controller;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.service.VerificationCodeService;
import com.example.demo.util.JwtUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;

@RestController
@RequestMapping("/api/auth")
public class AuthApiController {
    
    private static final Logger logger = LoggerFactory.getLogger(AuthApiController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private VerificationCodeService verificationCodeService;
    
    /**
     * 用户登录（已禁用，仅支持邮箱验证码登录）
     * 为了向后兼容，保留此接口但返回提示信息
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> credentials,
                                                    HttpServletRequest request,
                                                    HttpServletResponse response) {
        logger.warn("尝试使用用户名密码登录，但系统已禁用此方式");
        return ResponseEntity.badRequest()
            .body(createErrorResponse("系统已禁用用户名密码登录，请使用邮箱验证码登录"));
    }
    
    /**
     * 验证码登录（邮箱）
     */
    @PostMapping("/login/email")
    public ResponseEntity<Map<String, Object>> loginWithEmail(@RequestBody Map<String, String> credentials) {
        try {
            String email = credentials.get("email");
            String code = credentials.get("code");
            
            if (email == null || email.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("邮箱不能为空"));
            }
            
            if (code == null || code.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("验证码不能为空"));
            }
            
            // 验证邮箱验证码
            if (!verificationCodeService.verifyEmailCode(email, code)) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("验证码错误或已过期"));
            }
            
            // 查找用户，如果不存在则自动注册
            User user = userService.findByEmail(email);
            if (user == null) {
                // 自动注册新用户
                try {
                    // 从邮箱生成用户名（去掉@符号及后面的部分）
                    String username = email.split("@")[0];
                    logger.info("邮箱验证码登录 - 原始邮箱: '{}', 生成的用户名: '{}'", email, username);
                    
                    // 确保用户名长度不超过50个字符
                    if (username.length() > 50) {
                        username = username.substring(0, 50);
                        logger.info("邮箱验证码登录 - 用户名过长，截断为: '{}'", username);
                    }
                    // 确保用户名唯一
                    String originalUsername = username;
                    int counter = 1;
                    while (userService.findByUsernameOrNull(username) != null) {
                        // 如果用户名过长，需要重新截断
                        String newUsername = originalUsername + counter;
                        if (newUsername.length() > 50) {
                            newUsername = newUsername.substring(0, 50);
                        }
                        username = newUsername;
                        counter++;
                    }
                    
                    // 创建新用户
                    user = new User();
                    user.setUsername(username);
                    user.setEmail(email);
                    user.setPasswordHash(""); // 邮箱登录不需要密码
                    user.setRole("ROLE_USER"); // 默认为普通用户
                    user.setPoints(50); // 默认积分
                    user.setNickname(username); // 默认昵称为用户名
                    user.setIsActive(true);
                    
                    // 保存用户
                    user = userService.save(user);
                    
                    logger.info("自动注册新用户：{}", email);
                } catch (Exception e) {
                    logger.error("自动注册用户失败：{}", email, e);
                    return ResponseEntity.badRequest()
                        .body(createErrorResponse("用户注册失败：" + e.getMessage()));
                }
            }
            
            // 生成JWT Token
            String token = jwtUtils.generateToken(user.getUsername(), user.getRole(), user.getId());
            logger.info("邮箱验证码登录 - 生成JWT token，用户名: '{}', 用户ID: {}", user.getUsername(), user.getId());
            
            Map<String, Object> body = new HashMap<>();
            body.put("success", true);
            body.put("message", "登录成功");
            
            Map<String, Object> data = new HashMap<>();
            data.put("user", user);
            data.put("token", token);
            body.put("data", data);
            
            logger.info("用户邮箱验证码登录成功：{}", email);
            return ResponseEntity.ok(body);
            
        } catch (Exception e) {
            logger.error("邮箱验证码登录失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("登录失败：" + e.getMessage()));
        }
    }
    
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@Valid @RequestBody User user) {
        try {
            if (userService.findByUsername(user.getUsername()) != null) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("用户名已存在"));
            }
            
            if (userService.findByEmail(user.getEmail()) != null) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("邮箱已存在"));
            }
            
            User savedUser = userService.save(user);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "注册成功");
            response.put("data", savedUser);
            
            logger.info("用户注册成功：{}", user.getUsername());
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("注册失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("注册失败：" + e.getMessage()));
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "登出成功");
        
        logger.info("用户登出");
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public ResponseEntity<Map<String, Object>> getCurrentUser(Authentication authentication) {
        try {
            logger.info("获取当前用户信息 - authentication: {}", authentication);
            
            if (authentication != null && authentication.isAuthenticated()) {
                String username = authentication.getName();
                logger.info("当前用户名: {}", username);
                
                try {
                    User user = userService.findByUsername(username);
                    logger.info("找到用户: {}", user.getUsername());
                    
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("data", user);
                    return ResponseEntity.ok(response);
                } catch (Exception e) {
                    logger.error("查找用户失败: {}", username, e);
                    return ResponseEntity.badRequest()
                        .body(createErrorResponse("用户不存在: " + username));
                }
            }
            
            logger.info("用户未认证");
            return ResponseEntity.badRequest()
                .body(createErrorResponse("用户未登录"));
            
        } catch (Exception e) {
            logger.error("获取用户信息失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("获取用户信息失败: " + e.getMessage()));
        }
    }
    
    /**
     * 检查用户名是否存在
     */
    @GetMapping("/public/users/exists/username")
    public ResponseEntity<Map<String, Object>> checkUsernameExists(@RequestParam String value) {
        try {
            boolean exists = userService.findByUsername(value) != null;
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", Map.of("exists", exists));
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("检查用户名失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("检查用户名失败"));
        }
    }
    
    /**
     * 检查邮箱是否存在
     */
    @GetMapping("/public/users/exists/email")
    public ResponseEntity<Map<String, Object>> checkEmailExists(@RequestParam String value) {
        try {
            boolean exists = userService.findByEmail(value) != null;
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", Map.of("exists", exists));
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("检查邮箱失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("检查邮箱失败"));
        }
    }
    
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
}
