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

namespace TakeoutSaaS.AdminApi.Controllers;

/// <summary>
/// 用户权限洞察接口。
/// </summary>
[ApiVersion("1.0")]
[Authorize]
[Route("api/admin/v{version:apiVersion}/users/permissions")]
public sealed class UserPermissionsController(IAdminAuthService authService) : BaseApiController
{
    /// <summary>
    /// 分页查询当前租户用户的角色与权限概览。
    /// </summary>
    /// <remarks>
    /// 示例：
    /// <code>
    /// GET /api/admin/v1/users/permissions?keyword=ops&amp;page=1&amp;pageSize=20&amp;sortBy=createdAt&amp;sortDescending=true
    /// Header: Authorization: Bearer &lt;JWT&gt;
    /// 响应:
    /// {
    ///   "success": true,
    ///   "code": 200,
    ///   "data": {
    ///     "items": [
    ///       {
    ///         "userId": "900123456789012346",
    ///         "tenantId": "100000000000000001",
    ///         "merchantId": "200000000000000001",
    ///         "account": "ops.manager",
    ///         "displayName": "运营经理",
    ///         "roles": ["OpsManager", "Reporter"],
    ///         "permissions": ["delivery:read", "order:read", "payment:read"],
    ///         "createdAt": "2025-12-01T08:30:00Z"
    ///       }
    ///     ],
    ///     "page": 1,
    ///     "pageSize": 20,
    ///     "totalCount": 1,
    ///     "totalPages": 1
    ///   }
    /// }
    /// </code>
    /// </remarks>
    /// <param name="query">搜索条件。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>分页的用户权限概览。</returns>
    [HttpGet]
    [PermissionAuthorize("identity:permission:read")]
    [ProducesResponseType(typeof(ApiResponse<PagedResult<UserPermissionDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<UserPermissionDto>>> Search(
        [FromQuery] SearchUserPermissionsQuery query,
        CancellationToken cancellationToken)
    {
        // 1. 查询当前租户的用户权限概览
        var result = await authService.SearchUserPermissionsAsync(
            query.Keyword,
            query.Page,
            query.PageSize,
            query.SortBy,
            query.SortDescending,
            cancellationToken);

        // 2. 返回分页结果
        return ApiResponse<PagedResult<UserPermissionDto>>.Ok(result);
    }
}
