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

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

        return true;
    }
}
