using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using FutureMailAPI.DTOs;
using FutureMailAPI.Services;

namespace FutureMailAPI.Controllers
{
    [ApiController]
    [Route("api/v1/auth")]
    public class AuthController : BaseController
    {
        private readonly IAuthService _authService;
        private readonly IOAuthService _oauthService;
        private readonly ILogger<AuthController> _logger;

        public AuthController(IAuthService authService, IOAuthService oauthService, ILogger<AuthController> logger)
        {
            _authService = authService;
            _oauthService = oauthService;
            _logger = logger;
        }

        [HttpPost("register")]
        [AllowAnonymous]
        public async Task<IActionResult> Register([FromBody] UserRegisterDto registerDto)
        {
            try
            {
                var result = await _authService.RegisterAsync(registerDto);
                
                if (result.Success)
                {
                    return Ok(result);
                }
                
                return BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户注册时发生错误");
                return StatusCode(500, ApiResponse<UserResponseDto>.ErrorResult("服务器内部错误"));
            }
        }

        [HttpPost("login")]
        [AllowAnonymous]
        public async Task<IActionResult> Login([FromBody] UserLoginDto loginDto)
        {
            try
            {
                var result = await _authService.LoginAsync(loginDto);
                
                if (result.Success)
                {
                    return Ok(result);
                }
                
                return BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户登录时发生错误");
                return StatusCode(500, ApiResponse<UserResponseDto>.ErrorResult("服务器内部错误"));
            }
        }

        [HttpPost("logout")]
        public async Task<IActionResult> Logout()
        {
            try
            {
                // 获取当前令牌
                var authHeader = Request.Headers.Authorization.FirstOrDefault();
                if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer "))
                {
                    return BadRequest(new { message = "缺少授权令牌" });
                }

                var token = authHeader.Substring("Bearer ".Length).Trim();
                
                // 撤销令牌
                await _oauthService.RevokeTokenAsync(token);
                
                return Ok(new { message = "退出登录成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户退出登录时发生错误");
                return StatusCode(500, new { message = "服务器内部错误" });
            }
        }

        [HttpPost("token")]
        [AllowAnonymous]
        public async Task<IActionResult> GetToken([FromBody] OAuthLoginRequestDto request)
        {
            try
            {
                var result = await _oauthService.LoginAsync(request);
                
                if (result.Success)
                {
                    return Ok(result);
                }
                
                return BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "OAuth令牌获取时发生错误");
                return StatusCode(500, ApiResponse<OAuthTokenResponseDto>.ErrorResult("服务器内部错误"));
            }
        }

        [HttpPost("refresh")]
        [AllowAnonymous]
        public async Task<IActionResult> RefreshToken([FromBody] OAuthRefreshTokenRequestDto request)
        {
            try
            {
                var result = await _oauthService.RefreshTokenAsync(request);
                
                if (result.Success)
                {
                    return Ok(result);
                }
                
                return BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "OAuth令牌刷新时发生错误");
                return StatusCode(500, ApiResponse<OAuthTokenResponseDto>.ErrorResult("服务器内部错误"));
            }
        }

        [HttpPost("revoke")]
        [AllowAnonymous]
        public async Task<IActionResult> RevokeToken([FromBody] string accessToken)
        {
            try
            {
                var result = await _oauthService.RevokeTokenAsync(accessToken);
                
                if (result)
                {
                    return Ok(new { message = "令牌已成功撤销" });
                }
                
                return BadRequest(new { message = "无效的令牌" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "OAuth令牌撤销时发生错误");
                return StatusCode(500, new { message = "服务器内部错误" });
            }
        }

        [HttpGet("userinfo")]
        public async Task<IActionResult> GetUserInfo()
        {
            try
            {
                var userId = GetCurrentUserId();
                var userEmail = GetCurrentUserEmail();
                var username = GetCurrentUsername();
                var clientId = GetCurrentClientId();

                return Ok(new
                {
                    userId,
                    username,
                    email = userEmail,
                    clientId
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户信息时发生错误");
                return StatusCode(500, new { message = "服务器内部错误" });
            }
        }
    }
}