using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using QYZH.InteractiveMagazine.Infrastructure.Auth;
using QYZH.InteractiveMagazine.Models.Dto;
using QYZH.InteractiveMagazine.Models.Enum;
using System.Security.Claims;

namespace QYZH.InteractiveMagazine.WebApi.Controllers.WeChat;

/// <summary>
/// 小程序基础控制器
/// </summary>
[Authorize]
[ApiController]
[Route("wechat/api/[controller]")]
[ApiExplorerSettings(GroupName = nameof(ApiVersionEnum.Wechat))]
public abstract class WeChatBaseController : ControllerBase
{
    /// <summary>
    /// 获取当前激活用户ID（Users.Id，来自 JWT NameIdentifier）
    /// </summary>
    /// <returns>User ID（无激活用户时为 0）</returns>
    protected long GetCurrentUserId()
    {
        var userIdClaim = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
        if (userIdClaim != null && long.TryParse(userIdClaim.Value, out var userId))
        {
            return userId;
        }
        return 0;
    }

    /// <summary>
    /// 获取当前微信用户ID（WxUser.Id，来自 JWT WxUserId claim）
    /// </summary>
    /// <returns>WxUser ID</returns>
    protected long? GetCurrentWxUserId()
    {
        var wxUserIdClaim = User.Claims.FirstOrDefault(c => c.Type == JwtHelper.WxUserIdClaimType);
        if (wxUserIdClaim != null && long.TryParse(wxUserIdClaim.Value, out var wxUserId))
        {
            return wxUserId;
        }
        return null;
    }

    /// <summary>
    /// 获取当前用户名
    /// </summary>
    /// <returns>用户名</returns>
    protected string? GetCurrentUserName()
    {
        return User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
    }

    /// <summary>
    /// 成功响应
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    /// <param name="data">数据</param>
    /// <param name="message">提示信息</param>
    /// <returns>统一响应对象</returns>
    protected BaseResponse<T> Success<T>(T data, string message = "操作成功")
    {
        return BaseResponse<T>.Success(data, message);
    }

    /// <summary>
    /// 失败响应
    /// </summary>
    /// <param name="message">提示信息</param>
    /// <param name="code">状态码</param>
    /// <returns>统一响应对象</returns>
    protected BaseResponse<object> Fail(string message, int code = 500)
    {
        return BaseResponse<object>.Fail(ResultCode.GLOBAL_ERROR, message);
    }
}
