using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.SystemParameters.Commands;
using TakeoutSaaS.Domain.SystemParameters.Repositories;

namespace TakeoutSaaS.Application.App.SystemParameters.Handlers;

/// <summary>
/// 删除系统参数命令处理器。
/// </summary>
public sealed class DeleteSystemParameterCommandHandler(
    ISystemParameterRepository repository,
    ILogger<DeleteSystemParameterCommandHandler> logger)
    : IRequestHandler<DeleteSystemParameterCommand, bool>
{
    private readonly ISystemParameterRepository _repository = repository;
    private readonly ILogger<DeleteSystemParameterCommandHandler> _logger = logger;

    /// <inheritdoc />
    public async Task<bool> Handle(DeleteSystemParameterCommand request, CancellationToken cancellationToken)
    {
        var existing = await _repository.FindByIdAsync(request.ParameterId, cancellationToken);
        if (existing == null)
        {
            return false;
        }

        await _repository.RemoveAsync(existing, cancellationToken);
        await _repository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("删除系统参数 {Key}", existing.Key);
        return true;
    }
}
