using System.Security.Claims;
using HoneyBox.Admin.Filters;
using HoneyBox.Admin.Models.Auth;
using HoneyBox.Admin.Models.Common;
using HoneyBox.Admin.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Admin.Controllers;

/// <summary>
/// 认证控制器
/// </summary>
[ApiController]
[Route("api/admin/auth")]
public class AuthController : ControllerBase
{
    private readonly IAuthService _authService;
    private readonly ICaptchaService _captchaService;
    private readonly ILogger<AuthController> _logger;

    public AuthController(IAuthService authService, ICaptchaService captchaService, ILogger<AuthController> logger)
    {
        _authService = authService;
        _captchaService = captchaService;
        _logger = logger;
    }

    /// <summary>
    /// 获取验证码
    /// </summary>
    /// <returns>验证码Key和Base64图片</returns>
    [HttpPost("captcha")]
    [AllowAnonymous]
    public ApiResponse<CaptchaResponse> GetCaptcha()
    {
        var result = _captchaService.Generate();
        var response = new CaptchaResponse
        {
            CaptchaKey = result.CaptchaKey,
            CaptchaImage = result.CaptchaImage
        };
        return ApiResponse<CaptchaResponse>.Success(response);
    }

    /// <summary>
    /// 管理员登录
    /// </summary>
    /// <param name="request">登录请求</param>
    /// <returns>登录响应</returns>
    [HttpPost("login")]
    [AllowAnonymous]
    [OperationLog("认证", "登录")]
    public async Task<ApiResponse<LoginResponse>> Login([FromBody] LoginRequest request)
    {
        var ipAddress = GetClientIpAddress();
        var result = await _authService.LoginAsync(request, ipAddress);
        return ApiResponse<LoginResponse>.Success(result, "登录成功");
    }

    /// <summary>
    /// 刷新Token
    /// </summary>
    /// <param name="request">刷新Token请求</param>
    /// <returns>新的Token</returns>
    [HttpPost("refresh")]
    [AllowAnonymous]
    public async Task<ApiResponse<RefreshTokenResponse>> RefreshToken([FromBody] RefreshTokenRequest request)
    {
        var ipAddress = GetClientIpAddress();
        var result = await _authService.RefreshTokenAsync(request.RefreshToken, ipAddress);
        return ApiResponse<RefreshTokenResponse>.Success(result);
    }

    /// <summary>
    /// 获取当前用户信息
    /// </summary>
    /// <returns>用户信息</returns>
    [HttpGet("info")]
    [Authorize]
    public async Task<ApiResponse<AdminUserInfo>> GetInfo()
    {
        var userId = GetCurrentUserId();
        var result = await _authService.GetCurrentUserInfoAsync(userId);
        return ApiResponse<AdminUserInfo>.Success(result);
    }

    /// <summary>
    /// 修改密码
    /// </summary>
    /// <param name="request">修改密码请求</param>
    [HttpPut("password")]
    [Authorize]
    [OperationLog("认证", "修改密码")]
    public async Task<ApiResponse> ChangePassword([FromBody] ChangePasswordRequest request)
    {
        var userId = GetCurrentUserId();
        await _authService.ChangePasswordAsync(userId, request);
        return ApiResponse.Success("密码修改成功");
    }

    /// <summary>
    /// 退出登录
    /// </summary>
    /// <param name="request">退出登录请求（可选，包含RefreshToken）</param>
    [HttpPost("logout")]
    [Authorize]
    [OperationLog("认证", "退出登录")]
    public async Task<ApiResponse> Logout([FromBody] LogoutRequest? request = null)
    {
        var userId = GetCurrentUserId();
        var ipAddress = GetClientIpAddress();
        
        // 如果提供了RefreshToken，则撤销它
        if (!string.IsNullOrEmpty(request?.RefreshToken))
        {
            await _authService.RevokeTokenAsync(request.RefreshToken, ipAddress);
        }
        
        await _authService.LogoutAsync(userId);
        return ApiResponse.Success("退出成功");
    }

    /// <summary>
    /// 强制下线（撤销用户所有Token）
    /// </summary>
    [HttpPost("revoke-all")]
    [Authorize]
    [OperationLog("认证", "强制下线")]
    public async Task<ApiResponse> RevokeAllTokens()
    {
        var userId = GetCurrentUserId();
        var ipAddress = GetClientIpAddress();
        await _authService.RevokeAllTokensAsync(userId, ipAddress);
        return ApiResponse.Success("已撤销所有登录会话");
    }

    /// <summary>
    /// 获取当前用户ID
    /// </summary>
    private long GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
        if (userIdClaim == null || !long.TryParse(userIdClaim.Value, out var userId))
        {
            throw new AdminException(AdminErrorCodes.TokenInvalid, "无效的用户身份");
        }
        return userId;
    }

    /// <summary>
    /// 获取客户端IP地址
    /// </summary>
    private string GetClientIpAddress()
    {
        // 优先从 X-Forwarded-For 获取（反向代理场景）
        var forwardedFor = Request.Headers["X-Forwarded-For"].FirstOrDefault();
        if (!string.IsNullOrEmpty(forwardedFor))
        {
            return forwardedFor.Split(',')[0].Trim();
        }

        // 从 X-Real-IP 获取
        var realIp = Request.Headers["X-Real-IP"].FirstOrDefault();
        if (!string.IsNullOrEmpty(realIp))
        {
            return realIp;
        }

        // 从连接获取
        return HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
    }
}
