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

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 商户列表查询处理器。
/// </summary>
public sealed class GetMerchantListQueryHandler(
    IMerchantRepository merchantRepository,
    IStoreRepository storeRepository,
    ITenantRepository tenantRepository)
    : IRequestHandler<GetMerchantListQuery, PagedResult<MerchantListItemDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<MerchantListItemDto>> Handle(
        GetMerchantListQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 查询商户列表
        var merchants = await merchantRepository.SearchAsync(
            request.TenantId,
            request.Status,
            request.OperatingMode,
            request.Keyword,
            cancellationToken);

        if (merchants.Count == 0)
        {
            return new PagedResult<MerchantListItemDto>(Array.Empty<MerchantListItemDto>(), request.Page, request.PageSize, 0);
        }

        // 2. (空行后) 排序 & 分页
        var sorted = ApplySorting(merchants, request.SortBy, request.SortOrder);
        var total = sorted.Count;
        var paged = sorted
            .Skip((request.Page - 1) * request.PageSize)
            .Take(request.PageSize)
            .ToList();

        if (paged.Count == 0)
        {
            return new PagedResult<MerchantListItemDto>(Array.Empty<MerchantListItemDto>(), request.Page, request.PageSize, total);
        }

        // 3. (空行后) 批量查询租户名称
        var tenantIds = paged.Select(x => x.TenantId).Distinct().ToArray();
        var tenants = await tenantRepository.FindByIdsAsync(tenantIds, cancellationToken);
        var tenantLookup = tenants.ToDictionary(x => x.Id, x => x.Name);

        // 4. (空行后) 批量查询门店数量
        var merchantIds = paged.Select(x => x.Id).ToArray();
        var storeCounts = await storeRepository.GetStoreCountsAsync(request.TenantId, merchantIds, cancellationToken);

        // 5. (空行后) 组装 DTO
        var items = paged.Select(merchant =>
        {
            var tenantName = tenantLookup.TryGetValue(merchant.TenantId, out var name) ? name : null;
            var count = storeCounts.TryGetValue(merchant.Id, out var value) ? value : 0;
            return MerchantMapping.ToListItemDto(merchant, tenantName, count);
        }).ToList();

        return new PagedResult<MerchantListItemDto>(items, request.Page, request.PageSize, total);
    }

    private static List<Domain.Merchants.Entities.Merchant> ApplySorting(
        IReadOnlyList<Domain.Merchants.Entities.Merchant> merchants,
        string? sortBy,
        string? sortOrder)
    {
        var descending = !string.Equals(sortOrder, "asc", StringComparison.OrdinalIgnoreCase);
        return (sortBy ?? string.Empty).Trim().ToLowerInvariant() switch
        {
            "name" => descending ? merchants.OrderByDescending(x => x.BrandName).ToList() : merchants.OrderBy(x => x.BrandName).ToList(),
            "status" => descending ? merchants.OrderByDescending(x => x.Status).ToList() : merchants.OrderBy(x => x.Status).ToList(),
            "updatedat" => descending ? merchants.OrderByDescending(x => x.UpdatedAt ?? x.CreatedAt).ToList() : merchants.OrderBy(x => x.UpdatedAt ?? x.CreatedAt).ToList(),
            _ => descending ? merchants.OrderByDescending(x => x.CreatedAt).ToList() : merchants.OrderBy(x => x.CreatedAt).ToList()
        };
    }
}
