using MediatR;
using TakeoutSaaS.Application.Identity.Commands;
using TakeoutSaaS.Domain.Identity.Enums;
using TakeoutSaaS.Domain.Identity.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 删除租户角色命令处理器。
/// </summary>
public sealed class DeleteTenantRoleCommandHandler(IRoleRepository roleRepository)
    : IRequestHandler<DeleteTenantRoleCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteTenantRoleCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验角色存在
        var role = await roleRepository.FindByIdAsync(PortalType.Tenant, request.TenantId, request.RoleId, cancellationToken);
        if (role is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "角色不存在");
        }

        // 2. 执行软删除
        await roleRepository.DeleteAsync(PortalType.Tenant, request.TenantId, request.RoleId, cancellationToken);
        await roleRepository.SaveChangesAsync(cancellationToken);

        // 3. 返回成功
        return true;
    }
}
