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

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 门店列表查询处理器。
/// </summary>
public sealed class SearchStoresQueryHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SearchStoresQuery, PagedResult<StoreDto>>
{
    private readonly IStoreRepository _storeRepository = storeRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;

    /// <inheritdoc />
    public async Task<PagedResult<StoreDto>> Handle(SearchStoresQuery request, CancellationToken cancellationToken)
    {
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var stores = await _storeRepository.SearchAsync(tenantId, request.Status, cancellationToken);

        if (request.MerchantId.HasValue)
        {
            stores = stores.Where(x => x.MerchantId == request.MerchantId.Value).ToList();
        }

        var sorted = ApplySorting(stores, request.SortBy, request.SortDescending);
        var paged = sorted
            .Skip((request.Page - 1) * request.PageSize)
            .Take(request.PageSize)
            .ToList();

        var items = paged.Select(MapToDto).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)
        };
    }

    private static StoreDto MapToDto(Domain.Stores.Entities.Store store) => new()
    {
        Id = store.Id,
        TenantId = store.TenantId,
        MerchantId = store.MerchantId,
        Code = store.Code,
        Name = store.Name,
        Phone = store.Phone,
        ManagerName = store.ManagerName,
        Status = store.Status,
        Province = store.Province,
        City = store.City,
        District = store.District,
        Address = store.Address,
        Longitude = store.Longitude,
        Latitude = store.Latitude,
        Announcement = store.Announcement,
        Tags = store.Tags,
        DeliveryRadiusKm = store.DeliveryRadiusKm,
        SupportsDineIn = store.SupportsDineIn,
        SupportsPickup = store.SupportsPickup,
        SupportsDelivery = store.SupportsDelivery,
        SupportsReservation = store.SupportsReservation,
        SupportsQueueing = store.SupportsQueueing,
        CreatedAt = store.CreatedAt
    };
}
