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

namespace TakeoutSaaS.Application.App.Deliveries.Handlers;

/// <summary>
/// 删除配送单命令处理器。
/// </summary>
public sealed class DeleteDeliveryOrderCommandHandler(
    IDeliveryRepository deliveryRepository,
    ILogger<DeleteDeliveryOrderCommandHandler> logger)
    : IRequestHandler<DeleteDeliveryOrderCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteDeliveryOrderCommand request, CancellationToken cancellationToken)
    {
        // 1. 定位配送单（跨租户）
        var existing = await deliveryRepository.FindByIdAsync(request.DeliveryOrderId, cancellationToken);
        if (existing == null)
        {
            return false;
        }

        // 2. (空行后) 删除并保存
        await deliveryRepository.DeleteDeliveryOrderAsync(request.DeliveryOrderId, existing.TenantId, cancellationToken);
        await deliveryRepository.SaveChangesAsync(cancellationToken);

        // 3. (空行后) 记录删除日志
        logger.LogInformation("删除配送单 {DeliveryOrderId}", request.DeliveryOrderId);

        return true;
    }
}
