using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Domain.Stores.Entities;
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 UpdateStoreDeliveryZoneCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdateStoreDeliveryZoneCommandHandler> logger)
    : IRequestHandler<UpdateStoreDeliveryZoneCommand, StoreDeliveryZoneDto?>
{
    private readonly IStoreRepository _storeRepository = storeRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;
    private readonly ILogger<UpdateStoreDeliveryZoneCommandHandler> _logger = logger;

    /// <inheritdoc />
    public async Task<StoreDeliveryZoneDto?> Handle(UpdateStoreDeliveryZoneCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取区域
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var existing = await _storeRepository.FindDeliveryZoneByIdAsync(request.DeliveryZoneId, tenantId, cancellationToken);
        if (existing is null)
        {
            return null;
        }

        // 2. 校验门店归属
        if (existing.StoreId != request.StoreId)
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "配送区域不属于该门店");
        }

        // 3. 更新字段
        existing.ZoneName = request.ZoneName.Trim();
        existing.PolygonGeoJson = request.PolygonGeoJson.Trim();
        existing.MinimumOrderAmount = request.MinimumOrderAmount;
        existing.DeliveryFee = request.DeliveryFee;
        existing.EstimatedMinutes = request.EstimatedMinutes;
        existing.SortOrder = request.SortOrder;

        // 4. 持久化
        await _storeRepository.UpdateDeliveryZoneAsync(existing, cancellationToken);
        await _storeRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("更新配送区域 {DeliveryZoneId} 对应门店 {StoreId}", existing.Id, existing.StoreId);

        // 5. 返回 DTO
        return StoreMapping.ToDto(existing);
    }
}
