using MediatR;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Application.App.Stores.Queries;
using TakeoutSaaS.Application.App.Stores.Services;
using TakeoutSaaS.Domain.Stores.Enums;
using TakeoutSaaS.Domain.Stores.Repositories;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 租户端门店统计查询处理器。
/// </summary>
public sealed class GetStoreStatsQueryHandler(
    StoreContextService storeContextService,
    IStoreRepository storeRepository)
    : IRequestHandler<GetStoreStatsQuery, StoreStatsDto>
{
    /// <inheritdoc />
    public async Task<StoreStatsDto> Handle(GetStoreStatsQuery request, CancellationToken cancellationToken)
    {
        // 1. 解析上下文
        var context = storeContextService.GetRequiredContext();

        // 2. 查询当前商户全部门店
        var stores = await storeRepository.SearchAsync(
            context.TenantId,
            context.MerchantId,
            status: null,
            auditStatus: null,
            businessStatus: null,
            ownershipType: null,
            keyword: null,
            includeDeleted: false,
            cancellationToken: cancellationToken);

        // 3. 统计并返回
        return new StoreStatsDto
        {
            Total = stores.Count,
            Operating = stores.Count(store => store.BusinessStatus == StoreBusinessStatus.Open),
            Resting = stores.Count(store => store.BusinessStatus == StoreBusinessStatus.Resting),
            PendingAudit = stores.Count(store => store.AuditStatus == StoreAuditStatus.Pending)
        };
    }
}
