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

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 删除商品命令处理器。
/// </summary>
public sealed class DeleteProductCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider,
    ILogger<DeleteProductCommandHandler> logger)
    : IRequestHandler<DeleteProductCommand, bool>
{
    private readonly IProductRepository _productRepository = productRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;
    private readonly ILogger<DeleteProductCommandHandler> _logger = logger;

    /// <inheritdoc />
    public async Task<bool> Handle(DeleteProductCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验存在性
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var existing = await _productRepository.FindByIdAsync(request.ProductId, tenantId, cancellationToken);
        if (existing == null)
        {
            return false;
        }

        // 2. 删除
        await _productRepository.DeleteProductAsync(request.ProductId, tenantId, cancellationToken);
        await _productRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("删除商品 {ProductId}", request.ProductId);

        return true;
    }
}
