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

namespace TakeoutSaaS.Application.App.Deliveries.Handlers;

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

        // 2. 删除并保存
        await deliveryRepository.DeleteDeliveryOrderAsync(request.DeliveryOrderId, tenantId, cancellationToken);
        await deliveryRepository.SaveChangesAsync(cancellationToken);

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

        return true;
    }
}
