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

namespace TakeoutSaaS.Application.App.Orders.Handlers;

/// <summary>
/// 删除订单命令处理器。
/// </summary>
public sealed class DeleteOrderCommandHandler(
    IOrderRepository orderRepository,
    ILogger<DeleteOrderCommandHandler> logger)
    : IRequestHandler<DeleteOrderCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteOrderCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验存在性（跨租户）
        var existing = await orderRepository.FindByIdAsync(request.OrderId, cancellationToken);
        if (existing == null)
        {
            return false;
        }

        // 2. (空行后) 删除
        await orderRepository.DeleteOrderAsync(request.OrderId, existing.TenantId, cancellationToken);
        await orderRepository.SaveChangesAsync(cancellationToken);

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

        // 4. (空行后) 返回执行结果
        return true;
    }
}
