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

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 推荐/邀请控制器 - 处理用户邀请和推荐功能
/// </summary>
/// <remarks>
/// 提供邀请信息查询、邀请码绑定等功能
/// </remarks>
[ApiController]
[Route("api")]
public class InvitationController : ControllerBase
{
    private readonly IInvitationService _invitationService;
    private readonly ILogger<InvitationController> _logger;

    public InvitationController(
        IInvitationService invitationService,
        ILogger<InvitationController> logger)
    {
        _invitationService = invitationService;
        _logger = logger;
    }

    /// <summary>
    /// 获取推荐信息
    /// GET /api/invitation
    /// Requirements: 9.1-9.2
    /// </summary>
    [HttpGet("invitation")]
    [Authorize]
    public async Task<ApiResponse<InvitationInfoResponse>> GetInvitationInfo([FromQuery] int page = 1, [FromQuery] int pageSize = 10)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<InvitationInfoResponse>.Unauthorized();
        }

        try
        {
            if (page < 1) page = 1;

            // 从请求头获取平台类型
            var platform = Request.Headers["client"].FirstOrDefault();
            if (string.IsNullOrEmpty(platform))
            {
                platform = Request.Headers["platform"].FirstOrDefault() ?? "H5";
            }

            var result = await _invitationService.GetInvitationInfoAsync(userId.Value, page, platform);
            return ApiResponse<InvitationInfoResponse>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get invitation info: UserId={UserId}", userId);
            return ApiResponse<InvitationInfoResponse>.Fail("获取推荐信息失败");
        }
    }

    /// <summary>
    /// 绑定邀请码
    /// POST /api/bind_invite_code
    /// Requirements: 9.3-9.5
    /// </summary>
    [HttpPost("bind_invite_code")]
    [Authorize]
    public async Task<ApiResponse> BindInviteCode([FromBody] BindInviteCodeRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse.Unauthorized();
        }

        try
        {
            if (request == null || string.IsNullOrWhiteSpace(request.InviteCode))
            {
                return ApiResponse.Fail("缺少必要参数");
            }

            var result = await _invitationService.BindInviteCodeAsync(userId.Value, request.InviteCode);
            
            if (result.Success)
            {
                return ApiResponse.Success(result.Message);
            }
            else
            {
                return ApiResponse.Fail(result.Message);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to bind invite code: UserId={UserId}", userId);
            return ApiResponse.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
}
