using MediatR;
using TakeoutSaaS.Application.Identity.Commands;
using TakeoutSaaS.Application.Identity.Contracts;
using TakeoutSaaS.Domain.Identity.Repositories;
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 tenantId = request.TenantId ?? tenantProvider.GetCurrentTenantId();
        var role = await roleRepository.FindByIdAsync(request.RoleId, tenantId, cancellationToken);
        if (role == null)
        {
            return null;
        }

        // 2. 更新字段
        role.Name = request.Name;
        role.Description = request.Description;

        // 3. 持久化
        await roleRepository.UpdateAsync(role, cancellationToken);
        await roleRepository.SaveChangesAsync(cancellationToken);

        // 4. 返回 DTO
        return new RoleDto
        {
            Id = role.Id,
            TenantId = role.TenantId,
            Name = role.Name,
            Code = role.Code,
            Description = role.Description
        };
    }
}
