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 UpdateAdminRolePermissionsCommandHandler(
    IRoleRepository roleRepository,
    IRolePermissionRepository rolePermissionRepository)
    : IRequestHandler<UpdateAdminRolePermissionsCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(UpdateAdminRolePermissionsCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验角色存在
        var role = await roleRepository.FindByIdAsync(PortalType.Admin, null, request.RoleId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "角色不存在");

        // 2. 替换角色权限（事务保证）
        await rolePermissionRepository.ReplaceRolePermissionsAsync(
            PortalType.Admin,
            null,
            request.RoleId,
            request.PermissionIds,
            cancellationToken);

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