using MediatR;
using TakeoutSaaS.Application.Identity.Commands;
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 DeletePermissionCommandHandler(
    IPermissionRepository permissionRepository)
    : IRequestHandler<DeletePermissionCommand, bool>
{
    /// <summary>
    /// 处理删除权限请求。
    /// </summary>
    /// <param name="request">删除命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>执行结果。</returns>
    public async Task<bool> Handle(DeletePermissionCommand request, CancellationToken cancellationToken)
    {
        // 1. 权限固定时禁止删除
        if (!PermissionPolicy.CanMaintainPermissions)
        {
            throw new BusinessException(ErrorCodes.Forbidden, "权限已固定，禁止删除");
        }

        // 2. 删除权限
        await permissionRepository.DeleteAsync(request.PermissionId, cancellationToken);
        await permissionRepository.SaveChangesAsync(cancellationToken);

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