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 ReplaceProductPricingRulesCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider,
    ILogger<ReplaceProductPricingRulesCommandHandler> logger)
    : IRequestHandler<ReplaceProductPricingRulesCommand, IReadOnlyList<ProductPricingRuleDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<ProductPricingRuleDto>> Handle(ReplaceProductPricingRulesCommand 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.RemovePricingRulesAsync(request.ProductId, tenantId, cancellationToken);

        var rules = request.PricingRules.Select(r => new ProductPricingRule
        {
            ProductId = request.ProductId,
            RuleType = r.RuleType,
            ConditionsJson = r.ConditionsJson.Trim(),
            Price = r.Price,
            WeekdaysJson = r.WeekdaysJson,
            SortOrder = 0
        }).ToList();

        await productRepository.AddPricingRulesAsync(rules, cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("替换商品 {ProductId} 价格策略 {Count} 条", request.ProductId, rules.Count);

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