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

        // 2. 删除角色
        await roleRepository.DeleteAsync(request.RoleId, tenantId, cancellationToken);
        await roleRepository.SaveChangesAsync(cancellationToken);

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