using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Application.App.Stores.Queries;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 桌码上下文查询处理器。
/// </summary>
public sealed class GetStoreTableContextQueryHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<GetStoreTableContextQueryHandler> logger)
    : IRequestHandler<GetStoreTableContextQuery, StoreTableContextDto?>
{
    /// <inheritdoc />
    public async Task<StoreTableContextDto?> Handle(GetStoreTableContextQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询桌码
        var tenantId = tenantProvider.GetCurrentTenantId();
        var table = await storeRepository.FindTableByCodeAsync(request.TableCode, tenantId, cancellationToken);
        if (table is null)
        {
            logger.LogWarning("未找到桌码 {TableCode}", request.TableCode);
            return null;
        }

        // 2. 查询门店
        var store = await storeRepository.FindByIdAsync(table.StoreId, tenantId, cancellationToken);
        if (store is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "门店不存在");
        }

        // 3. 组装上下文
        return new StoreTableContextDto
        {
            StoreId = store.Id,
            StoreName = store.Name,
            Announcement = store.Announcement,
            Tags = store.Tags,
            TableId = table.Id,
            TableCode = table.TableCode,
            AreaId = table.AreaId,
            Capacity = table.Capacity,
            TableTags = table.Tags,
            Status = table.Status
        };
    }
}
