using MediatR;
using TakeoutSaaS.Application.Identity.Commands;
using TakeoutSaaS.Domain.Identity.Repositories;

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 删除角色模板处理器。
/// </summary>
public sealed class DeleteRoleTemplateCommandHandler(IRoleTemplateRepository roleTemplateRepository)
    : IRequestHandler<DeleteRoleTemplateCommand, bool>
{
    /// <summary>
    /// 处理删除角色模板请求。
    /// </summary>
    /// <param name="request">删除命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>执行结果。</returns>
    public async Task<bool> Handle(DeleteRoleTemplateCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询模板
        var template = await roleTemplateRepository.FindByCodeAsync(request.TemplateCode, cancellationToken);
        if (template == null)
        {
            return false;
        }

        // 2. 删除并保存
        await roleTemplateRepository.DeleteAsync(template.Id, cancellationToken);
        await roleTemplateRepository.SaveChangesAsync(cancellationToken);

        // 3. 返回执行结果
        return true;
    }
}
