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

namespace TakeoutSaaS.Application.App.Orders.Handlers;

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

        // 2. 删除
        await orderRepository.DeleteOrderAsync(request.OrderId, tenantId, cancellationToken);
        await orderRepository.SaveChangesAsync(cancellationToken);

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

        // 4. 返回执行结果
        return true;
    }
}
