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 AssignUserRolesCommandHandler(
    IUserRoleRepository userRoleRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<AssignUserRolesCommand, bool>
{
    /// <summary>
    /// 处理用户角色分配请求。
    /// </summary>
    /// <param name="request">分配命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>执行结果。</returns>
    public async Task<bool> Handle(AssignUserRolesCommand request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文
        var tenantId = tenantProvider.GetCurrentTenantId();

        // 2. 覆盖式绑定角色
        await userRoleRepository.ReplaceUserRolesAsync(tenantId, request.UserId, request.RoleIds, cancellationToken);
        await userRoleRepository.SaveChangesAsync(cancellationToken);

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