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 DeleteStorePickupSlotCommandHandler(
    IStoreRepository storeRepository,
    ILogger<DeleteStorePickupSlotCommandHandler> logger)
    : IRequestHandler<DeleteStorePickupSlotCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteStorePickupSlotCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取门店并解析租户
        var store = await storeRepository.FindByIdAsync(request.StoreId, tenantId: null, cancellationToken);
        if (store is null)
        {
            return false;
        }
        var tenantId = store.TenantId;

        // 2. (空行后) 校验档期归属
        var slot = await storeRepository.FindPickupSlotByIdAsync(request.SlotId, tenantId, cancellationToken);
        if (slot is null || slot.StoreId != request.StoreId)
        {
            return false;
        }

        // 3. (空行后) 删除档期
        await storeRepository.DeletePickupSlotAsync(request.SlotId, tenantId, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("删除自提档期 {SlotId}", request.SlotId);
        return true;
    }
}
