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

    /// <inheritdoc />
    public async Task<bool> Handle(DeleteStoreBusinessHourCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取时段
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var existing = await _storeRepository.FindBusinessHourByIdAsync(request.BusinessHourId, tenantId, cancellationToken);
        if (existing is null)
        {
            return false;
        }

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

        // 3. 删除
        await _storeRepository.DeleteBusinessHourAsync(request.BusinessHourId, tenantId, cancellationToken);
        await _storeRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("删除营业时段 {BusinessHourId} 对应门店 {StoreId}", request.BusinessHourId, request.StoreId);

        return true;
    }
}
