using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Application.Identity.Abstractions;
using TakeoutSaaS.Application.Identity.Contracts;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Results;
using TakeoutSaaS.Shared.Web.Api;
using TakeoutSaaS.Shared.Web.Security;

namespace TakeoutSaaS.MiniApi.Controllers;

/// <summary>
/// 当前用户信息
/// </summary>
/// <remarks>提供小程序端当前用户档案查询。</remarks>
/// <param name="authService">小程序认证服务</param>
[ApiVersion("1.0")]
[Authorize]
[Route("api/mini/v{version:apiVersion}/me")]
public sealed class MeController(IMiniAuthService authService) : BaseApiController
{
    /// <summary>
    /// 获取用户档案
    /// </summary>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>当前用户档案信息。</returns>
    [HttpGet]
    [ProducesResponseType(typeof(ApiResponse<CurrentUserProfile>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<CurrentUserProfile>), StatusCodes.Status401Unauthorized)]
    public async Task<ApiResponse<CurrentUserProfile>> Get(CancellationToken cancellationToken)
    {
        // 1. 从 JWT 中解析用户标识
        var userId = User.GetUserId();
        if (userId == 0)
        {
            return ApiResponse<CurrentUserProfile>.Error(ErrorCodes.Unauthorized, "Token 缺少有效的用户标识");
        }

        // 2. 查询用户档案并返回
        var profile = await authService.GetProfileAsync(userId, cancellationToken);
        return ApiResponse<CurrentUserProfile>.Ok(profile);
    }
}
