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.Application.App.Stores.Services;
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 CreateStoreDeliveryZoneCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    IGeoJsonValidationService geoJsonValidationService,
    ILogger<CreateStoreDeliveryZoneCommandHandler> logger)
    : IRequestHandler<CreateStoreDeliveryZoneCommand, StoreDeliveryZoneDto>
{
    /// <inheritdoc />
    public async Task<StoreDeliveryZoneDto> Handle(CreateStoreDeliveryZoneCommand 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;

        // 2. (空行后) 校验 GeoJSON
        var validation = geoJsonValidationService.ValidatePolygon(request.PolygonGeoJson);
        if (!validation.IsValid)
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, validation.ErrorMessage ?? "配送范围格式错误");
        }

        // 3. (空行后) 构建实体
        var zone = new StoreDeliveryZone
        {
            TenantId = storeTenantId,
            StoreId = request.StoreId,
            ZoneName = request.ZoneName.Trim(),
            PolygonGeoJson = (validation.NormalizedGeoJson ?? request.PolygonGeoJson).Trim(),
            MinimumOrderAmount = request.MinimumOrderAmount,
            DeliveryFee = request.DeliveryFee,
            EstimatedMinutes = request.EstimatedMinutes,
            Color = request.Color?.Trim(),
            Priority = request.Priority,
            SortOrder = request.SortOrder
        };

        // 4. (空行后) 持久化
        await storeRepository.AddDeliveryZonesAsync(new[] { zone }, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("创建配送区域 {DeliveryZoneId} 对应门店 {StoreId}", zone.Id, request.StoreId);

        // 5. (空行后) 返回 DTO
        return StoreMapping.ToDto(zone);
    }
}
