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

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 兑换码控制器 - 处理兑换码使用功能
/// </summary>
/// <remarks>
/// 提供兑换码验证和使用功能
/// </remarks>
[ApiController]
[Route("api")]
public class RedeemController : ControllerBase
{
    private readonly IRedeemService _redeemService;
    private readonly ILogger<RedeemController> _logger;

    public RedeemController(
        IRedeemService redeemService,
        ILogger<RedeemController> logger)
    {
        _redeemService = redeemService;
        _logger = logger;
    }

    /// <summary>
    /// 使用兑换码
    /// POST /api/redeem_code
    /// Requirements: 11.1
    /// </summary>
    [HttpPost("redeem_code")]
    [Authorize]
    public async Task<ApiResponse<RedeemResult>> UseRedeemCode([FromBody] UseRedeemCodeRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<RedeemResult>.Unauthorized();
        }

        try
        {
            if (request == null || string.IsNullOrWhiteSpace(request.Code))
            {
                return ApiResponse<RedeemResult>.Fail("请输入兑换码");
            }

            var result = await _redeemService.UseRedeemCodeAsync(userId.Value, request.Code);

            if (result.Success)
            {
                return ApiResponse<RedeemResult>.Success(result, result.Message);
            }
            else
            {
                return ApiResponse<RedeemResult>.Fail(result.Message);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to use redeem code: UserId={UserId}", userId);
            return ApiResponse<RedeemResult>.Fail("兑换失败，请稍后重试");
        }
    }

    /// <summary>
    /// 获取兑换记录
    /// GET /api/redeem_record
    /// Requirements: 11.2
    /// </summary>
    [HttpGet("redeem_record")]
    [Authorize]
    public async Task<ApiResponse<RedeemRecordResponse>> GetRedeemRecord([FromQuery] int page = 1, [FromQuery] int pageSize = 10)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<RedeemRecordResponse>.Unauthorized();
        }

        try
        {
            var result = await _redeemService.GetRedeemRecordAsync(userId.Value, page, pageSize);
            return ApiResponse<RedeemRecordResponse>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get redeem record: UserId={UserId}", userId);
            return ApiResponse<RedeemRecordResponse>.Fail("获取兑换记录失败，请稍后重试");
        }
    }

    /// <summary>
    /// 使用兑换码（旧版兼容接口）
    /// POST /api/used
    /// Requirements: 11.1
    /// </summary>
    [HttpPost("used")]
    [Authorize]
    public async Task<ApiResponse<RedeemResult>> UseRedeemCodeLegacy([FromBody] UseRedeemCodeRequest? request)
    {
        // 调用新接口实现
        return await UseRedeemCode(request);
    }

    #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
}
