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

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 商城控制器 - 处理钻石商品和订单功能
/// </summary>
/// <remarks>
/// 提供钻石商品列表、创建钻石订单、查询订单状态等功能
/// Requirements: 15.1-15.3
/// </remarks>
[ApiController]
[Route("api")]
public class MallController : ControllerBase
{
    private readonly IMallService _mallService;
    private readonly ILogger<MallController> _logger;

    public MallController(
        IMallService mallService,
        ILogger<MallController> logger)
    {
        _mallService = mallService;
        _logger = logger;
    }

    /// <summary>
    /// 获取钻石商品列表
    /// GET /api/get_diamond_list
    /// Requirements: 15.1
    /// </summary>
    [HttpGet("get_diamond_list")]
    public async Task<ApiResponse<List<DiamondProductDto>>> GetDiamondList()
    {
        try
        {
            // 尝试获取当前用户ID（可选，用于判断首充状态）
            var userId = GetCurrentUserId();

            var result = await _mallService.GetDiamondListAsync(userId);
            return ApiResponse<List<DiamondProductDto>>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get diamond list");
            return ApiResponse<List<DiamondProductDto>>.Fail("获取钻石商品列表失败，请稍后重试");
        }
    }

    /// <summary>
    /// 创建钻石订单
    /// GET /api/createOrderProducts
    /// Requirements: 15.2
    /// </summary>
    /// <remarks>
    /// 注意：PHP原接口使用GET方法，为保持兼容性这里也使用GET
    /// </remarks>
    [HttpGet("createOrderProducts")]
    [Authorize]
    public async Task<ApiResponse<CreateDiamondOrderResult>> CreateOrderProducts(
        [FromQuery(Name = "product_id")] string productId,
        [FromQuery(Name = "pay_type")] int payType = 2)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<CreateDiamondOrderResult>.Unauthorized();
        }

        try
        {
            if (string.IsNullOrWhiteSpace(productId))
            {
                return ApiResponse<CreateDiamondOrderResult>.Fail("商品ID不能为空");
            }

            var request = new CreateDiamondOrderRequest
            {
                ProductId = productId,
                PayType = payType
            };

            var result = await _mallService.CreateOrderProductsAsync(userId.Value, request);

            if (result.Status == 1)
            {
                return ApiResponse<CreateDiamondOrderResult>.Success(result, "下单成功");
            }
            else
            {
                return ApiResponse<CreateDiamondOrderResult>.Fail("下单失败，请稍后重试");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create diamond order: UserId={UserId}, ProductId={ProductId}",
                userId, productId);
            return ApiResponse<CreateDiamondOrderResult>.Fail("下单失败，请稍后重试");
        }
    }

    /// <summary>
    /// 获取钻石订单状态
    /// GET /api/get_diamond_order_log
    /// Requirements: 15.3
    /// </summary>
    [HttpGet("get_diamond_order_log")]
    [Authorize]
    public async Task<ApiResponse<string>> GetDiamondOrderLog([FromQuery(Name = "order_num")] string orderNum)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<string>.Unauthorized();
        }

        try
        {
            if (string.IsNullOrWhiteSpace(orderNum))
            {
                return ApiResponse<string>.Fail("订单号不能为空");
            }

            var result = await _mallService.GetDiamondOrderLogAsync(userId.Value, orderNum);

            if (result == null)
            {
                return ApiResponse<string>.Fail("订单不存在或未成功");
            }

            // 返回奖励日志（与PHP保持一致）
            return ApiResponse<string>.Success(result.RewardLog ?? string.Empty);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get diamond order log: UserId={UserId}, OrderNum={OrderNum}",
                userId, orderNum);
            return ApiResponse<string>.Fail("查询订单状态失败，请稍后重试");
        }
    }

    #region Private Helper Methods

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

    #endregion
}
