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

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 删除配送区域处理器。
/// </summary>
public sealed class DeleteStoreDeliveryZoneCommandHandler(
    IStoreRepository storeRepository,
    ILogger<DeleteStoreDeliveryZoneCommandHandler> logger)
    : IRequestHandler<DeleteStoreDeliveryZoneCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteStoreDeliveryZoneCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取区域
        var existing = await storeRepository.FindDeliveryZoneByIdAsync(request.DeliveryZoneId, null, cancellationToken);
        if (existing is null)
        {
            return false;
        }

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

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

        return true;
    }
}
