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

namespace TakeoutSaaS.MiniApi.Controllers;

/// <summary>
/// 小程序登录认证
/// </summary>
/// <remarks>提供小程序端的微信登录与 Token 刷新能力。</remarks>
/// <param name="authService">小程序认证服务</param>
[ApiVersion("1.0")]
[Authorize]
[Route("api/mini/v{version:apiVersion}/auth")]
public sealed class AuthController(IMiniAuthService authService) : BaseApiController
{
    /// <summary>
    /// 微信登录
    /// </summary>
    /// <param name="request">微信登录请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>包含访问令牌与刷新令牌的响应。</returns>
    [HttpPost("wechat/login")]
    [AllowAnonymous]
    [ProducesResponseType(typeof(ApiResponse<TokenResponse>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<TokenResponse>> LoginWithWeChat([FromBody] WeChatLoginRequest request, CancellationToken cancellationToken)
    {
        // 1. 调用认证服务完成微信登录
        var response = await authService.LoginWithWeChatAsync(request, cancellationToken);

        // 2. 返回访问与刷新令牌
        return ApiResponse<TokenResponse>.Ok(response);
    }

    /// <summary>
    /// 刷新 Token
    /// </summary>
    /// <param name="request">刷新令牌请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>新的访问令牌与刷新令牌。</returns>
    [HttpPost("refresh")]
    [AllowAnonymous]
    [ProducesResponseType(typeof(ApiResponse<TokenResponse>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<TokenResponse>> RefreshToken([FromBody] RefreshTokenRequest request, CancellationToken cancellationToken)
    {
        // 1. 调用认证服务刷新 Token
        var response = await authService.RefreshTokenAsync(request, cancellationToken);

        // 2. 返回新的令牌
        return ApiResponse<TokenResponse>.Ok(response);
    }
}
