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

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 商品下架处理器。
/// </summary>
public sealed class UnpublishProductCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider,
    ILogger<UnpublishProductCommandHandler> logger)
    : IRequestHandler<UnpublishProductCommand, ProductDto?>
{
    /// <inheritdoc />
    public async Task<ProductDto?> Handle(UnpublishProductCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取商品
        var tenantId = tenantProvider.GetCurrentTenantId();
        var product = await productRepository.FindByIdAsync(request.ProductId, tenantId, cancellationToken);
        if (product is null)
        {
            return null;
        }

        // 2. 下架
        product.Status = ProductStatus.OffShelf;
        await productRepository.UpdateProductAsync(product, cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("商品下架 {ProductId}", product.Id);

        return ProductMapping.ToDto(product);
    }
}
