using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Application.App.Products;
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 SoldoutProductCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider,
    ILogger<SoldoutProductCommandHandler> logger)
    : IRequestHandler<SoldoutProductCommand, ProductDto?>
{
    /// <inheritdoc />
    public async Task<ProductDto?> Handle(SoldoutProductCommand request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var product = await productRepository.FindByIdAsync(request.ProductId, tenantId, cancellationToken);
        if (product is null)
        {
            return null;
        }

        product.Status = ProductStatus.OffShelf;
        product.SoldoutMode = request.Mode;
        product.RemainStock = Math.Max(0, request.RemainStock);
        product.StockQuantity = Math.Max(0, request.RemainStock);
        product.SoldoutReason = string.IsNullOrWhiteSpace(request.Reason) ? null : request.Reason.Trim();
        product.RecoverAt = request.Mode == ProductSoldoutMode.Timed ? request.RecoverAt : null;
        product.SyncToPlatform = request.SyncToPlatform;
        product.NotifyManager = request.NotifyManager;

        await productRepository.UpdateProductAsync(product, cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("商品沽清 {ProductId}，模式 {Mode}", product.Id, request.Mode);

        return ProductMapping.ToDto(product);
    }
}
