using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
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 UpdateStoreFeeCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdateStoreFeeCommandHandler> logger)
    : IRequestHandler<UpdateStoreFeeCommand, StoreFeeDto>
{
    /// <inheritdoc />
    public async Task<StoreFeeDto> Handle(UpdateStoreFeeCommand 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, "门店不存在");
        }
        var storeTenantId = store.TenantId;
        if (store.AuditStatus != StoreAuditStatus.Activated)
        {
            throw new BusinessException(ErrorCodes.Conflict, "门店未激活，无法配置费用");
        }
        if (store.BusinessStatus == StoreBusinessStatus.ForceClosed)
        {
            throw new BusinessException(ErrorCodes.Conflict, "门店已被强制关闭，无法配置费用");
        }

        // 2. (空行后) 获取或创建费用配置
        var fee = await storeRepository.GetStoreFeeAsync(request.StoreId, tenantId, cancellationToken);
        var isNew = fee is null;
        fee ??= new StoreFee
        {
            StoreId = request.StoreId,
            TenantId = storeTenantId
        };

        // 3. (空行后) 应用更新字段
        fee.MinimumOrderAmount = request.MinimumOrderAmount;
        fee.BaseDeliveryFee = request.DeliveryFee;
        fee.PlatformServiceRate = request.PlatformServiceRate;
        fee.PackagingFeeMode = request.PackagingFeeMode;
        fee.OrderPackagingFeeMode = request.PackagingFeeMode == PackagingFeeMode.Fixed
            ? request.OrderPackagingFeeMode
            : OrderPackagingFeeMode.Fixed;
        fee.FixedPackagingFee = request.FixedPackagingFee ?? 0m;
        // 非生效模式下也保留配置，避免模式切换后历史阶梯被清空。
        var normalizedTiers = StoreFeeTierHelper.Normalize(request.PackagingFeeTiers);
        fee.PackagingFeeTiersJson = StoreFeeTierHelper.Serialize(normalizedTiers);
        fee.FreeDeliveryThreshold = request.FreeDeliveryThreshold;
        fee.CutleryFeeEnabled = request.CutleryFeeEnabled;
        fee.CutleryFeeAmount = request.CutleryFeeAmount;
        fee.RushFeeEnabled = request.RushFeeEnabled;
        fee.RushFeeAmount = request.RushFeeAmount;

        // 4. (空行后) 保存并返回
        if (isNew)
        {
            await storeRepository.AddStoreFeeAsync(fee, cancellationToken);
        }
        else
        {
            await storeRepository.UpdateStoreFeeAsync(fee, cancellationToken);
        }
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("更新门店 {StoreId} 费用配置", request.StoreId);
        return StoreMapping.ToDto(fee);
    }
}
