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

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 商户列表查询处理器。
/// </summary>
public sealed class SearchMerchantsQueryHandler(
    IMerchantRepository merchantRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SearchMerchantsQuery, PagedResult<MerchantDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<MerchantDto>> Handle(SearchMerchantsQuery request, CancellationToken cancellationToken)
    {
        // 1. 获取租户并查询商户
        var tenantId = tenantProvider.GetCurrentTenantId();
        var merchants = await merchantRepository.SearchAsync(tenantId, request.Status, cancellationToken);

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

        // 3. 映射 DTO
        var items = paged.Select(merchant => new MerchantDto
        {
            Id = merchant.Id,
            TenantId = merchant.TenantId,
            BrandName = merchant.BrandName,
            BrandAlias = merchant.BrandAlias,
            LogoUrl = merchant.LogoUrl,
            Category = merchant.Category,
            ContactPhone = merchant.ContactPhone,
            ContactEmail = merchant.ContactEmail,
            Status = merchant.Status,
            JoinedAt = merchant.JoinedAt,
            CreatedAt = merchant.CreatedAt
        }).ToList();

        // 4. 返回分页结果
        return new PagedResult<MerchantDto>(items, request.Page, request.PageSize, merchants.Count);
    }

    private static IOrderedEnumerable<Domain.Merchants.Entities.Merchant> ApplySorting(
        IReadOnlyCollection<Domain.Merchants.Entities.Merchant> merchants,
        string? sortBy,
        bool sortDescending)
    {
        return sortBy?.ToLowerInvariant() switch
        {
            "brandname" => sortDescending
                ? merchants.OrderByDescending(x => x.BrandName)
                : merchants.OrderBy(x => x.BrandName),
            "status" => sortDescending
                ? merchants.OrderByDescending(x => x.Status)
                : merchants.OrderBy(x => x.Status),
            _ => sortDescending
                ? merchants.OrderByDescending(x => x.CreatedAt)
                : merchants.OrderBy(x => x.CreatedAt)
        };
    }
}
