package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.util.JwtUtils;
import jakarta.validation.Valid;
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.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/auth")
public class AuthApiController {
    
    private static final Logger logger = LoggerFactory.getLogger(AuthApiController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> credentials,
                                                    HttpServletRequest request,
                                                    HttpServletResponse response) {
        try {
            String username = credentials.get("username");
            String password = credentials.get("password");
            
            if (username == null || password == null) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("用户名和密码不能为空"));
            }
            
            // 使用Spring Security进行认证
            UsernamePasswordAuthenticationToken authToken = 
                new UsernamePasswordAuthenticationToken(username, password);
            Authentication authentication = authenticationManager.authenticate(authToken);
            
            User user = userService.findByUsername(username);
            
            // 生成JWT Token
            String token = jwtUtils.generateToken(username, user.getRole(), 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("用户登录成功：{}", username);
            return ResponseEntity.ok(body);
            
        } catch (Exception e) {
            logger.error("登录失败：", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("用户名或密码错误"));
        }
    }
    
    /**
     * 用户注册
     */
    @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;
    }
}
