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

    /// <inheritdoc />
    public async Task<bool> Handle(DeleteStoreHolidayCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取配置
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var existing = await _storeRepository.FindHolidayByIdAsync(request.HolidayId, tenantId, cancellationToken);
        if (existing is null)
        {
            return false;
        }

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

        // 3. 删除
        await _storeRepository.DeleteHolidayAsync(request.HolidayId, tenantId, cancellationToken);
        await _storeRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("删除节假日 {HolidayId} 对应门店 {StoreId}", request.HolidayId, request.StoreId);

        return true;
    }
}
