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

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 绑定角色权限处理器。
/// </summary>
public sealed class BindRolePermissionsCommandHandler(
    IRolePermissionRepository rolePermissionRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<BindRolePermissionsCommand, bool>
{
    /// <summary>
    /// 处理角色权限绑定请求。
    /// </summary>
    /// <param name="request">绑定命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>执行结果。</returns>
    public async Task<bool> Handle(BindRolePermissionsCommand request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文
        var currentTenantId = tenantProvider.GetCurrentTenantId();
        if (currentTenantId <= 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "缺少租户标识");
        }

        // 2. (空行后) 禁止跨租户操作
        if (request.TenantId.HasValue && request.TenantId.Value != currentTenantId)
        {
            throw new BusinessException(ErrorCodes.Forbidden, "禁止跨租户操作角色权限");
        }

        // 3. (空行后) 覆盖式绑定权限
        var tenantId = currentTenantId;

        var distinctPermissionIds = request.PermissionIds
            .Where(id => id > 0)
            .Distinct()
            .ToArray();

        await rolePermissionRepository.ReplaceRolePermissionsAsync(tenantId, request.RoleId, distinctPermissionIds, cancellationToken);
        await rolePermissionRepository.SaveChangesAsync(cancellationToken);

        // 4. (空行后) 返回执行结果
        return true;
    }
}
