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

namespace TakeoutSaaS.Application.App.Stores.Handlers;

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

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

        // 3. 按服务方式二次过滤
        var filtered = request.ServiceType.HasValue
            ? stores.Where(store => StoreListMapping.MatchServiceType(store, request.ServiceType.Value)).ToList()
            : stores.ToList();

        // 4. 按创建时间倒序并分页
        var page = request.Page <= 0 ? 1 : request.Page;
        var pageSize = request.PageSize <= 0 ? 10 : request.PageSize;
        var ordered = filtered
            .OrderByDescending(store => store.CreatedAt)
            .ToList();
        var items = ordered
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .Select(StoreListMapping.ToListItemDto)
            .ToList();

        // 5. 返回分页结构
        return new StoreListResultDto
        {
            Items = items,
            Total = filtered.Count,
            Page = page,
            PageSize = pageSize
        };
    }
}
