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 DeleteStoreTableCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<DeleteStoreTableCommandHandler> logger)
    : IRequestHandler<DeleteStoreTableCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteStoreTableCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取桌码
        var tenantId = tenantProvider.GetCurrentTenantId();
        var table = await storeRepository.FindTableByIdAsync(request.TableId, tenantId, cancellationToken);
        if (table is null || table.StoreId != request.StoreId)
        {
            return false;
        }

        // 2. 删除
        await storeRepository.DeleteTableAsync(request.TableId, tenantId, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("删除桌码 {TableId} 对应门店 {StoreId}", request.TableId, request.StoreId);

        return true;
    }
}
