package com.lingyue.auth.controller;

import com.lingyue.auth.dto.AuthResponse;
import com.lingyue.auth.dto.LoginRequest;
import com.lingyue.auth.dto.RegisterRequest;
import com.lingyue.auth.entity.User;
import com.lingyue.auth.service.AuthService;
import com.lingyue.auth.service.UserService;
import com.lingyue.common.domain.AjaxResult;
import com.lingyue.common.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 * 
 * @author lingyue
 * @since 2026-01-14
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Tag(name = "认证接口", description = "用户认证相关接口")
public class AuthController {
    
    private final AuthService authService;
    private final UserService userService;
    
    @Value("${jwt.secret:lingyue-zhibao-secret-key-2024-please-change-in-production}")
    private String jwtSecret;
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    @ResponseStatus(org.springframework.http.HttpStatus.CREATED)
    public AjaxResult<?> register(@Valid @RequestBody RegisterRequest request) {
        AuthResponse response = authService.register(request);
        return AjaxResult.success("注册成功", response);
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public AjaxResult<AuthResponse> login(
            @Valid @RequestBody LoginRequest request,
            HttpServletRequest httpRequest) {
        String ipAddress = getClientIpAddress(httpRequest);
        String userAgent = httpRequest.getHeader("User-Agent");
        AuthResponse response = authService.login(request, ipAddress, userAgent);
        return AjaxResult.success("登录成功", response);
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public AjaxResult<?> logout(@RequestHeader("Authorization") String authorization) {
        String token = authorization.replace("Bearer ", "");
        authService.logout(token);
        return AjaxResult.success("登出成功");
    }
    
    /**
     * 刷新Token
     */
    @PostMapping("/refresh")
    @Operation(summary = "刷新Token", description = "使用刷新Token获取新的访问Token")
    public AjaxResult<AuthResponse> refreshToken(@RequestBody RefreshTokenRequest request) {
        AuthResponse response = authService.refreshToken(request.getRefreshToken());
        return AjaxResult.success(response);
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    @Operation(summary = "获取当前用户", description = "根据Token获取当前登录用户信息")
    public AjaxResult<?> getCurrentUser(
            @RequestHeader(value = "Authorization", required = false) String authorization) {
        
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            return AjaxResult.error("未提供有效的认证Token");
        }
        
        String token = authorization.substring(7);
        
        try {
            // 从Token中解析用户ID
            String userId = JwtUtil.getUserIdFromToken(token, jwtSecret);
            if (userId == null) {
                return AjaxResult.error("Token无效或已过期");
            }
            
            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                return AjaxResult.error("用户不存在");
            }
            
            // 构建响应（不返回敏感信息）
            UserInfoResponse response = new UserInfoResponse();
            response.setId(user.getId());
            response.setUsername(user.getUsername());
            response.setEmail(user.getEmail());
            response.setAvatarUrl(user.getAvatarUrl());
            response.setRole(user.getRole());
            response.setLastLoginAt(user.getLastLoginAt());
            response.setCreateTime(user.getCreateTime());
            
            return AjaxResult.success(response);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage());
            return AjaxResult.error("Token无效或已过期");
        }
    }
    
    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            return xForwardedFor.split(",")[0].trim();
        }
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty()) {
            return xRealIp;
        }
        return request.getRemoteAddr();
    }
    
    /**
     * 刷新Token请求DTO
     */
    @Data
    @lombok.NoArgsConstructor
    @lombok.AllArgsConstructor
    public static class RefreshTokenRequest {
        private String refreshToken;
    }
    
    /**
     * 用户信息响应DTO
     */
    @Data
    public static class UserInfoResponse {
        private String id;
        private String username;
        private String email;
        private String avatarUrl;
        private String role;
        private java.util.Date lastLoginAt;
        private java.util.Date createTime;
    }
}

