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

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 更新商品命令处理器。
/// </summary>
public sealed class UpdateProductCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdateProductCommandHandler> logger)
    : IRequestHandler<UpdateProductCommand, ProductDto?>
{
    private readonly IProductRepository _productRepository = productRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;
    private readonly ILogger<UpdateProductCommandHandler> _logger = logger;

    /// <inheritdoc />
    public async Task<ProductDto?> Handle(UpdateProductCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取商品
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var existing = await _productRepository.FindByIdAsync(request.ProductId, tenantId, cancellationToken);
        if (existing == null)
        {
            return null;
        }

        // 2. 更新字段
        existing.StoreId = request.StoreId;
        existing.CategoryId = request.CategoryId;
        existing.SpuCode = request.SpuCode.Trim();
        existing.Name = request.Name.Trim();
        existing.Subtitle = request.Subtitle?.Trim();
        existing.Unit = request.Unit?.Trim();
        existing.Price = request.Price;
        existing.OriginalPrice = request.OriginalPrice;
        existing.StockQuantity = request.StockQuantity;
        existing.MaxQuantityPerOrder = request.MaxQuantityPerOrder;
        existing.Status = request.Status;
        existing.Kind = request.Kind;
        existing.SalesMonthly = request.SalesMonthly;
        existing.TagsJson = request.TagsJson?.Trim();
        existing.SoldoutMode = request.SoldoutMode;
        existing.RecoverAt = request.RecoverAt;
        existing.RemainStock = request.RemainStock;
        existing.SoldoutReason = request.SoldoutReason?.Trim();
        existing.SyncToPlatform = request.SyncToPlatform;
        existing.NotifyManager = request.NotifyManager;
        existing.TimedOnShelfAt = request.TimedOnShelfAt;
        existing.CoverImage = request.CoverImage?.Trim();
        existing.GalleryImages = request.GalleryImages?.Trim();
        existing.Description = request.Description?.Trim();
        existing.SortWeight = request.SortWeight;
        existing.WarningStock = request.WarningStock;
        existing.PackingFee = request.PackingFee;
        existing.EnableDineIn = request.EnableDineIn;
        existing.EnablePickup = request.EnablePickup;
        existing.EnableDelivery = request.EnableDelivery;
        existing.IsFeatured = request.IsFeatured;

        // 3. 持久化
        await _productRepository.UpdateProductAsync(existing, cancellationToken);
        await _productRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("更新商品 {ProductId} - {ProductName}", existing.Id, existing.Name);

        // 4. 返回 DTO
        return MapToDto(existing);
    }

    private static ProductDto MapToDto(Product product) => new()
    {
        Id = product.Id,
        TenantId = product.TenantId,
        StoreId = product.StoreId,
        CategoryId = product.CategoryId,
        SpuCode = product.SpuCode,
        Name = product.Name,
        Subtitle = product.Subtitle,
        Unit = product.Unit,
        Price = product.Price,
        OriginalPrice = product.OriginalPrice,
        StockQuantity = product.StockQuantity,
        MaxQuantityPerOrder = product.MaxQuantityPerOrder,
        Status = product.Status,
        Kind = product.Kind,
        SalesMonthly = product.SalesMonthly,
        TagsJson = product.TagsJson,
        SoldoutMode = product.SoldoutMode,
        RecoverAt = product.RecoverAt,
        RemainStock = product.RemainStock,
        SoldoutReason = product.SoldoutReason,
        SyncToPlatform = product.SyncToPlatform,
        NotifyManager = product.NotifyManager,
        TimedOnShelfAt = product.TimedOnShelfAt,
        CoverImage = product.CoverImage,
        GalleryImages = product.GalleryImages,
        Description = product.Description,
        SortWeight = product.SortWeight,
        WarningStock = product.WarningStock,
        PackingFee = product.PackingFee,
        EnableDineIn = product.EnableDineIn,
        EnablePickup = product.EnablePickup,
        EnableDelivery = product.EnableDelivery,
        IsFeatured = product.IsFeatured,
        CreatedAt = product.CreatedAt
    };
}
