using MediatR;
using TakeoutSaaS.Application.Identity.Commands;
using TakeoutSaaS.Application.Identity.Contracts;
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 UpdateRoleCommandHandler(
    IRoleRepository roleRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<UpdateRoleCommand, RoleDto?>
{
    /// <summary>
    /// 执行角色更新。
    /// </summary>
    /// <param name="request">更新命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>更新后的角色 DTO 或 null。</returns>
    public async Task<RoleDto?> Handle(UpdateRoleCommand 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 role = await roleRepository.FindByIdAsync(request.RoleId, tenantId, cancellationToken);
        if (role == null)
        {
            return null;
        }

        // 4. (空行后) 更新字段
        role.Name = request.Name;
        role.Description = request.Description;

        // 5. (空行后) 持久化
        await roleRepository.UpdateAsync(role, cancellationToken);
        await roleRepository.SaveChangesAsync(cancellationToken);

        // 6. (空行后) 返回 DTO
        return new RoleDto
        {
            Id = role.Id,
            TenantId = role.TenantId,
            Name = role.Name,
            Code = role.Code,
            Description = role.Description
        };
    }
}
