using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 删除配送区域处理器。
/// </summary>
public sealed class DeleteStoreDeliveryZoneCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<DeleteStoreDeliveryZoneCommandHandler> logger)
    : IRequestHandler<DeleteStoreDeliveryZoneCommand, bool>
{
    private readonly IStoreRepository _storeRepository = storeRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;
    private readonly ILogger<DeleteStoreDeliveryZoneCommandHandler> _logger = logger;

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

        // 2. 校验门店归属
        if (existing.StoreId != request.StoreId)
        {
            return false;
        }

        // 3. 删除
        await _storeRepository.DeleteDeliveryZoneAsync(request.DeliveryZoneId, tenantId, cancellationToken);
        await _storeRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("删除配送区域 {DeliveryZoneId} 对应门店 {StoreId}", request.DeliveryZoneId, request.StoreId);

        return true;
    }
}
