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 CreateStoreDeliveryZoneCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<CreateStoreDeliveryZoneCommandHandler> logger)
    : IRequestHandler<CreateStoreDeliveryZoneCommand, StoreDeliveryZoneDto>
{
    private readonly IStoreRepository _storeRepository = storeRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;
    private readonly ILogger<CreateStoreDeliveryZoneCommandHandler> _logger = logger;

    /// <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, "门店不存在");
        }

        // 2. 构建实体
        var zone = new StoreDeliveryZone
        {
            StoreId = request.StoreId,
            ZoneName = request.ZoneName.Trim(),
            PolygonGeoJson = request.PolygonGeoJson.Trim(),
            MinimumOrderAmount = request.MinimumOrderAmount,
            DeliveryFee = request.DeliveryFee,
            EstimatedMinutes = request.EstimatedMinutes,
            SortOrder = request.SortOrder
        };

        // 3. 持久化
        await _storeRepository.AddDeliveryZonesAsync(new[] { zone }, cancellationToken);
        await _storeRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("创建配送区域 {DeliveryZoneId} 对应门店 {StoreId}", zone.Id, request.StoreId);

        // 4. 返回 DTO
        return StoreMapping.ToDto(zone);
    }
}
