using System.Security.Claims;
using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Base;
using HoneyBox.Model.Models.Payment;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 支付控制器
/// 处理微信支付统一下单、余额支付、充值等支付相关接口
/// Requirements: 1.1-1.5, 2.1-2.6
/// </summary>
[ApiController]
[Route("api")]
public class PayController : ControllerBase
{
    private readonly IWechatPayService _wechatPayService;
    private readonly IRechargeService _rechargeService;
    private readonly IPaymentNotifyService _paymentNotifyService;
    private readonly ILogger<PayController> _logger;

    public PayController(
        IWechatPayService wechatPayService,
        IRechargeService rechargeService,
        IPaymentNotifyService paymentNotifyService,
        ILogger<PayController> logger)
    {
        _wechatPayService = wechatPayService;
        _rechargeService = rechargeService;
        _paymentNotifyService = paymentNotifyService;
        _logger = logger;
    }

    /// <summary>
    /// 微信支付回调接口（兼容旧路由）
    /// POST /api/pay/notify
    /// 接收微信支付结果通知，处理订单状态更新
    /// </summary>
    [HttpPost("pay/notify")]
    public async Task<IActionResult> PayNotify()
    {
        try
        {
            // 读取请求体
            using var reader = new StreamReader(Request.Body);
            var notifyBody = await reader.ReadToEndAsync();

            _logger.LogInformation("收到微信支付回调请求 [/api/pay/notify]，数据长度: {Length}, ContentType: {ContentType}", 
                notifyBody?.Length ?? 0, Request.ContentType);

            // 提取 V3 回调请求头（如果存在）
            WechatPayNotifyHeaders? headers = null;
            if (Request.Headers.TryGetValue("Wechatpay-Timestamp", out var timestamp) &&
                Request.Headers.TryGetValue("Wechatpay-Nonce", out var nonce) &&
                Request.Headers.TryGetValue("Wechatpay-Signature", out var signature) &&
                Request.Headers.TryGetValue("Wechatpay-Serial", out var serial))
            {
                headers = new WechatPayNotifyHeaders
                {
                    Timestamp = timestamp.ToString(),
                    Nonce = nonce.ToString(),
                    Signature = signature.ToString(),
                    Serial = serial.ToString()
                };
                _logger.LogDebug("检测到 V3 回调请求头: Timestamp={Timestamp}, Serial={Serial}", 
                    headers.Timestamp, headers.Serial);
            }

            // 调用服务处理回调（自动识别 V2/V3 格式）
            var result = await _paymentNotifyService.HandleWechatNotifyAsync(notifyBody ?? string.Empty, headers);

            _logger.LogInformation("微信支付回调处理完成: Success={Success}, Message={Message}",
                result.Success, result.Message);

            // 根据回调版本返回对应格式的响应
            if (!string.IsNullOrEmpty(result.JsonResponse))
            {
                // V3 返回 JSON
                return Content(result.JsonResponse, "application/json");
            }
            else
            {
                // V2 返回 XML
                return Content(result.XmlResponse ?? "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>", "application/xml");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理微信支付回调异常");

            // 返回成功响应，避免微信重复通知
            var successResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            return Content(successResponse, "application/xml");
        }
    }

    /// <summary>
    /// 微信支付统一下单接口
    /// POST /api/pay
    /// </summary>
    [HttpPost("pay")]
    [Authorize]
    public async Task<IActionResult> CreatePayment([FromBody] PayRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return Ok(new WechatPayResult { Status = 0, Msg = "请先登录" });
        }

        try
        {
            if (request == null)
                return Ok(new WechatPayResult { Status = 0, Msg = "请求参数不能为空" });

            if (string.IsNullOrWhiteSpace(request.OrderNo))
                return Ok(new WechatPayResult { Status = 0, Msg = "订单号不能为空" });

            if (request.Amount <= 0)
                return Ok(new WechatPayResult { Status = 0, Msg = "支付金额必须大于0" });

            if (string.IsNullOrWhiteSpace(request.Attach))
                return Ok(new WechatPayResult { Status = 0, Msg = "订单类型不能为空" });

            var wechatPayRequest = new WechatPayRequest
            {
                OrderNo = request.OrderNo,
                Amount = request.Amount,
                Body = string.IsNullOrWhiteSpace(request.Body) ? "商品购买" : request.Body,
                Attach = request.Attach,
                OpenId = request.OpenId ?? string.Empty,
                UserId = userId.Value
            };

            var result = await _wechatPayService.CreatePaymentAsync(wechatPayRequest);
            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "支付请求处理异常");
            return Ok(new WechatPayResult { Status = 0, Msg = "系统错误，请稍后重试" });
        }
    }

    /// <summary>
    /// 微信支付接口（兼容旧接口）
    /// POST /api/wx_pay
    /// </summary>
    [HttpPost("wx_pay")]
    [Authorize]
    public async Task<IActionResult> WxPay([FromBody] PayRequest? request)
    {
        return await CreatePayment(request);
    }

    /// <summary>
    /// 余额支付接口
    /// POST /api/balance_pay
    /// </summary>
    [HttpPost("balance_pay")]
    [Authorize]
    public async Task<IActionResult> BalancePay([FromBody] BalancePayRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return Ok(ApiResponse.Fail("请先登录", -1));
        }

        try
        {
            if (request == null)
                return Ok(ApiResponse.Fail("请求参数不能为空"));

            if (string.IsNullOrWhiteSpace(request.OrderNum))
                return Ok(ApiResponse.Fail("订单号不能为空"));

            if (request.Amount <= 0)
                return Ok(ApiResponse.Fail("支付金额必须大于0"));

            var result = await _rechargeService.BalancePayAsync(userId.Value, request.OrderNum, request.Amount);
            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "余额支付处理异常");
            return Ok(ApiResponse.Fail("系统错误，请稍后重试"));
        }
    }

    /// <summary>
    /// 充值接口
    /// POST /api/recharge
    /// </summary>
    [HttpPost("recharge")]
    [Authorize]
    public async Task<IActionResult> Recharge([FromBody] RechargeRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return Ok(ApiResponse.Fail("请先登录", -1));
        }

        try
        {
            if (request == null)
                return Ok(ApiResponse.Fail("请求参数不能为空"));

            if (request.Money <= 0)
                return Ok(ApiResponse.Fail("充值金额必须大于0"));

            var result = await _rechargeService.CreateRechargeOrderAsync(userId.Value, request.Money);
            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "充值处理异常");
            return Ok(ApiResponse.Fail("系统错误，请稍后重试"));
        }
    }

    /// <summary>
    /// 获取充值配置
    /// GET /api/recharge_config
    /// </summary>
    [HttpGet("recharge_config")]
    public async Task<IActionResult> GetRechargeConfig()
    {
        try
        {
            var config = await _rechargeService.GetRechargeConfigAsync();
            return Ok(ApiResponse<RechargeConfigResponse>.Success(config));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取充值配置异常");
            return Ok(ApiResponse.Fail("系统错误，请稍后重试"));
        }
    }

    /// <summary>
    /// 创建充值订单
    /// POST /api/create_recharge_order
    /// </summary>
    [HttpPost("create_recharge_order")]
    [Authorize]
    public async Task<IActionResult> CreateRechargeOrder([FromBody] CreateRechargeOrderRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return Ok(ApiResponse.Fail("请先登录", -1));
        }

        try
        {
            if (request == null)
                return Ok(ApiResponse.Fail("请求参数不能为空"));

            if (request.Money <= 0)
                return Ok(ApiResponse.Fail("充值金额必须大于0"));

            var result = await _rechargeService.CreateRechargeOrderAsync(userId.Value, request.Money);
            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建充值订单异常");
            return Ok(ApiResponse.Fail("系统错误，请稍后重试"));
        }
    }

    /// <summary>
    /// 查询支付状态
    /// GET /api/query_pay_status
    /// </summary>
    [HttpGet("query_pay_status")]
    [Authorize]
    public async Task<IActionResult> QueryPayStatus([FromQuery] string? order_num)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return Ok(ApiResponse.Fail("请先登录", -1));
        }

        try
        {
            if (string.IsNullOrWhiteSpace(order_num))
                return Ok(ApiResponse.Fail("订单号不能为空"));

            var result = await _rechargeService.QueryPayStatusAsync(order_num);
            return Ok(ApiResponse<PayStatusResponse>.Success(result));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "查询支付状态异常");
            return Ok(ApiResponse.Fail("系统错误，请稍后重试"));
        }
    }

    /// <summary>
    /// 获取当前登录用户ID
    /// </summary>
    private int? GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        if (int.TryParse(userIdClaim, out var userId))
        {
            return userId;
        }
        return null;
    }
}

/// <summary>
/// 支付请求（前端传入）
/// </summary>
public class PayRequest
{
    /// <summary>
    /// 订单号
    /// </summary>
    public string OrderNo { get; set; } = string.Empty;

    /// <summary>
    /// 支付金额
    /// </summary>
    public decimal Amount { get; set; }

    /// <summary>
    /// 商品描述
    /// </summary>
    public string? Body { get; set; }

    /// <summary>
    /// 附加数据（订单类型）
    /// </summary>
    public string Attach { get; set; } = string.Empty;

    /// <summary>
    /// 用户OpenId
    /// </summary>
    public string? OpenId { get; set; }
}
