using MediatR;
using TakeoutSaaS.Application.Identity.Commands;
using TakeoutSaaS.Application.Identity.Contracts;
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 UpdateTenantRoleCommandHandler(IRoleRepository roleRepository)
    : IRequestHandler<UpdateTenantRoleCommand, RoleDto?>
{
    /// <inheritdoc />
    public async Task<RoleDto?> Handle(UpdateTenantRoleCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验必填字段
        if (string.IsNullOrWhiteSpace(request.Name))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "角色名称不能为空");
        }

        // 2. 查询目标角色
        var role = await roleRepository.FindByIdAsync(PortalType.Tenant, request.TenantId, request.RoleId, cancellationToken);
        if (role is null)
        {
            return null;
        }

        // 3. 更新字段
        role.Name = request.Name.Trim();
        role.Description = request.Description;

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

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