using MediatR;
using TakeoutSaaS.Application.Identity.Commands;
using TakeoutSaaS.Domain.Identity.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 绑定角色权限处理器。
/// </summary>
public sealed class BindRolePermissionsCommandHandler(
    IRolePermissionRepository rolePermissionRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<BindRolePermissionsCommand, bool>
{
    /// <summary>
    /// 处理角色权限绑定请求。
    /// </summary>
    /// <param name="request">绑定命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>执行结果。</returns>
    public async Task<bool> Handle(BindRolePermissionsCommand request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文
        var tenantId = request.TenantId ?? tenantProvider.GetCurrentTenantId();

        // 2. 覆盖式绑定权限
        var distinctPermissionIds = request.PermissionIds
            .Where(id => id > 0)
            .Distinct()
            .ToArray();

        await rolePermissionRepository.ReplaceRolePermissionsAsync(tenantId, request.RoleId, distinctPermissionIds, cancellationToken);
        await rolePermissionRepository.SaveChangesAsync(cancellationToken);

        // 3. 返回执行结果
        return true;
    }
}
