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;

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 更新角色模板处理器。
/// </summary>
public sealed class UpdateRoleTemplateCommandHandler(IRoleTemplateRepository roleTemplateRepository)
    : IRequestHandler<UpdateRoleTemplateCommand, RoleTemplateDto?>
{
    /// <inheritdoc />
    public async Task<RoleTemplateDto?> Handle(UpdateRoleTemplateCommand request, CancellationToken cancellationToken)
    {
        if (string.IsNullOrWhiteSpace(request.TemplateCode) || string.IsNullOrWhiteSpace(request.Name))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "模板编码与名称不能为空");
        }

        var template = await roleTemplateRepository.FindByCodeAsync(request.TemplateCode, cancellationToken);
        if (template == null)
        {
            return null;
        }

        template.Name = request.Name.Trim();
        template.Description = request.Description;
        template.IsActive = request.IsActive;

        var permissions = request.PermissionCodes
            .Where(code => !string.IsNullOrWhiteSpace(code))
            .Select(code => code.Trim())
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .ToArray();

        await roleTemplateRepository.UpdateAsync(template, permissions, cancellationToken);
        await roleTemplateRepository.SaveChangesAsync(cancellationToken);

        return TemplateMapper.ToDto(template, permissions);
    }
}
