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.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 替换媒资处理器。
/// </summary>
public sealed class ReplaceProductMediaCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider,
    ILogger<ReplaceProductMediaCommandHandler> logger)
    : IRequestHandler<ReplaceProductMediaCommand, IReadOnlyList<ProductMediaAssetDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<ProductMediaAssetDto>> Handle(ReplaceProductMediaCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验商品
        var tenantId = tenantProvider.GetCurrentTenantId();
        var product = await productRepository.FindByIdAsync(request.ProductId, tenantId, cancellationToken);
        if (product is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "商品不存在");
        }

        // 2. 替换
        await productRepository.RemoveMediaAssetsAsync(request.ProductId, tenantId, cancellationToken);

        var assets = request.MediaAssets.Select(a => new ProductMediaAsset
        {
            ProductId = request.ProductId,
            MediaType = a.MediaType,
            Url = a.Url.Trim(),
            Caption = a.Caption?.Trim(),
            SortOrder = a.SortOrder
        }).ToList();

        await productRepository.AddMediaAssetsAsync(assets, cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("替换商品 {ProductId} 媒资 {Count} 条", request.ProductId, assets.Count);

        return assets.Select(ProductMapping.ToDto).ToList();
    }
}
