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

    /// <inheritdoc />
    public async Task<bool> Handle(DeleteStoreCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验存在性
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var existing = await _storeRepository.FindByIdAsync(request.StoreId, tenantId, cancellationToken);
        if (existing == null)
        {
            return false;
        }

        // 2. 删除
        await _storeRepository.DeleteStoreAsync(request.StoreId, tenantId, cancellationToken);
        await _storeRepository.SaveChangesAsync(cancellationToken);
        _logger.LogInformation("删除门店 {StoreId}", request.StoreId);

        return true;
    }
}
