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

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 商品列表查询处理器。
/// </summary>
public sealed class SearchProductsQueryHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SearchProductsQuery, PagedResult<ProductDto>>
{
    private readonly IProductRepository _productRepository = productRepository;
    private readonly ITenantProvider _tenantProvider = tenantProvider;

    /// <inheritdoc />
    public async Task<PagedResult<ProductDto>> Handle(SearchProductsQuery request, CancellationToken cancellationToken)
    {
        var tenantId = _tenantProvider.GetCurrentTenantId();
        var products = await _productRepository.SearchAsync(tenantId, request.StoreId, request.CategoryId, request.Status, cancellationToken);

        var sorted = ApplySorting(products, 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<ProductDto>(items, request.Page, request.PageSize, products.Count);
    }

    private static IOrderedEnumerable<Domain.Products.Entities.Product> ApplySorting(
        IReadOnlyCollection<Domain.Products.Entities.Product> products,
        string? sortBy,
        bool sortDescending)
    {
        return sortBy?.ToLowerInvariant() switch
        {
            "name" => sortDescending ? products.OrderByDescending(x => x.Name) : products.OrderBy(x => x.Name),
            "price" => sortDescending ? products.OrderByDescending(x => x.Price) : products.OrderBy(x => x.Price),
            "status" => sortDescending ? products.OrderByDescending(x => x.Status) : products.OrderBy(x => x.Status),
            _ => sortDescending ? products.OrderByDescending(x => x.CreatedAt) : products.OrderBy(x => x.CreatedAt)
        };
    }

    private static ProductDto MapToDto(Domain.Products.Entities.Product product) => new()
    {
        Id = product.Id,
        TenantId = product.TenantId,
        StoreId = product.StoreId,
        CategoryId = product.CategoryId,
        SpuCode = product.SpuCode,
        Name = product.Name,
        Subtitle = product.Subtitle,
        Unit = product.Unit,
        Price = product.Price,
        OriginalPrice = product.OriginalPrice,
        StockQuantity = product.StockQuantity,
        MaxQuantityPerOrder = product.MaxQuantityPerOrder,
        Status = product.Status,
        CoverImage = product.CoverImage,
        GalleryImages = product.GalleryImages,
        Description = product.Description,
        EnableDineIn = product.EnableDineIn,
        EnablePickup = product.EnablePickup,
        EnableDelivery = product.EnableDelivery,
        IsFeatured = product.IsFeatured,
        CreatedAt = product.CreatedAt
    };
}
