using MediatR;
using TakeoutSaaS.Application.App.Stores;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Application.App.Stores.Queries;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Shared.Abstractions.Results;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 门店列表查询处理器。
/// </summary>
public sealed class SearchStoresQueryHandler(
    IStoreRepository storeRepository)
    : IRequestHandler<SearchStoresQuery, PagedResult<StoreDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<StoreDto>> Handle(SearchStoresQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询门店列表（可选租户过滤）
        var stores = await storeRepository.SearchAsync(
            request.TenantId,
            request.MerchantId,
            request.Status,
            request.AuditStatus,
            request.BusinessStatus,
            request.OwnershipType,
            request.Keyword,
            request.IncludeDeleted,
            cancellationToken);

        // 2. (空行后) 排序与分页
        var sorted = ApplySorting(stores, request.SortBy, request.SortDescending);
        var paged = sorted
            .Skip((request.Page - 1) * request.PageSize)
            .Take(request.PageSize)
            .ToList();

        // 3. (空行后) 映射 DTO
        var items = paged.Select(StoreMapping.ToDto).ToList();
        return new PagedResult<StoreDto>(items, request.Page, request.PageSize, stores.Count);
    }

    private static IOrderedEnumerable<Domain.Stores.Entities.Store> ApplySorting(
        IReadOnlyCollection<Domain.Stores.Entities.Store> stores,
        string? sortBy,
        bool sortDescending)
    {
        return sortBy?.ToLowerInvariant() switch
        {
            "name" => sortDescending ? stores.OrderByDescending(x => x.Name) : stores.OrderBy(x => x.Name),
            "code" => sortDescending ? stores.OrderByDescending(x => x.Code) : stores.OrderBy(x => x.Code),
            "status" => sortDescending ? stores.OrderByDescending(x => x.Status) : stores.OrderBy(x => x.Status),
            _ => sortDescending ? stores.OrderByDescending(x => x.CreatedAt) : stores.OrderBy(x => x.CreatedAt)
        };
    }

}
