using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Models.Payment;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 支付回调控制器
/// 处理微信支付等第三方支付平台的回调通知
/// </summary>
[ApiController]
[Route("api/notify")]
public class NotifyController : ControllerBase
{
    private readonly IPaymentNotifyService _paymentNotifyService;
    private readonly ILogger<NotifyController> _logger;

    public NotifyController(
        IPaymentNotifyService paymentNotifyService,
        ILogger<NotifyController> logger)
    {
        _paymentNotifyService = paymentNotifyService;
        _logger = logger;
    }

    /// <summary>
    /// 微信支付回调接口（支持 V2 XML 和 V3 JSON 格式）
    /// POST /api/notify/order_notify
    /// 接收微信支付结果通知，处理订单状态更新
    /// </summary>
    [HttpPost("order_notify")]
    public async Task<IActionResult> OrderNotify()
    {
        try
        {
            // 读取请求体
            using var reader = new StreamReader(Request.Body);
            var notifyBody = await reader.ReadToEndAsync();

            _logger.LogInformation("收到微信支付回调请求，数据长度: {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");
        }
    }
}
