using MediatR;
using MktXService.Domain.AggregatesModel.SampleAggregate;

namespace MktXService.API.Application.Commands;

/// <summary>
/// EN: Handler for DeleteSampleCommand.
/// VI: Handler cho DeleteSampleCommand.
/// </summary>
public class DeleteSampleCommandHandler : IRequestHandler<DeleteSampleCommand, bool>
{
    private readonly ISampleRepository _sampleRepository;
    private readonly ILogger<DeleteSampleCommandHandler> _logger;

    public DeleteSampleCommandHandler(
        ISampleRepository sampleRepository,
        ILogger<DeleteSampleCommandHandler> logger)
    {
        _sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<bool> Handle(
        DeleteSampleCommand request,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Deleting sample {SampleId} / Xóa sample {SampleId}",
            request.SampleId);

        // EN: Get existing sample / VI: Lấy sample đã tồn tại
        var sample = await _sampleRepository.GetAsync(request.SampleId);

        if (sample is null)
        {
            _logger.LogWarning(
                "Sample {SampleId} not found / Sample {SampleId} không tìm thấy",
                request.SampleId);
            return false;
        }

        // EN: Delete sample / VI: Xóa sample
        _sampleRepository.Delete(sample);

        // EN: Save changes / VI: Lưu thay đổi
        await _sampleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation(
            "Sample {SampleId} deleted successfully / Sample {SampleId} đã xóa thành công",
            request.SampleId);

        return true;
    }
}
