using MediatR;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Application.App.Stores.Queries;
using TakeoutSaaS.Application.App.Stores.Services;
using TakeoutSaaS.Domain.Stores.Entities;
using TakeoutSaaS.Domain.Stores.Enums;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 门店费用预览查询处理器。
/// </summary>
public sealed class CalculateStoreFeeQueryHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    IStoreFeeCalculationService feeCalculationService)
    : IRequestHandler<CalculateStoreFeeQuery, StoreFeeCalculationResultDto>
{
    /// <inheritdoc />
    public async Task<StoreFeeCalculationResultDto> Handle(CalculateStoreFeeQuery request, CancellationToken cancellationToken)
    {
        // 1. 校验门店存在
        var tenantId = tenantProvider.GetCurrentTenantId();
        var store = await storeRepository.FindByIdAsync(request.StoreId, tenantId, cancellationToken);
        if (store is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "门店不存在");
        }

        // 2. (空行后) 获取费用配置
        var fee = await storeRepository.GetStoreFeeAsync(request.StoreId, tenantId, cancellationToken)
                  ?? new StoreFee
                  {
                      StoreId = request.StoreId,
                      MinimumOrderAmount = 0m,
                      BaseDeliveryFee = 0m,
                      PackagingFeeMode = PackagingFeeMode.Fixed,
                      OrderPackagingFeeMode = OrderPackagingFeeMode.Fixed,
                      FixedPackagingFee = 0m
                  };

        // 3. (空行后) 执行费用计算
        var calculationRequest = new StoreFeeCalculationRequestDto
        {
            OrderAmount = request.OrderAmount,
            ItemCount = request.ItemCount,
            Items = request.Items
        };
        return feeCalculationService.Calculate(fee, calculationRequest);
    }
}
