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

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 商品列表查询处理器。
/// </summary>
public sealed class SearchProductsQueryHandler(
    IProductRepository productRepository)
    : IRequestHandler<SearchProductsQuery, PagedResult<ProductDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<ProductDto>> Handle(SearchProductsQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询商品列表（可选租户过滤）
        var products = await productRepository.SearchAsync(
            request.TenantId,
            request.StoreId,
            request.CategoryId,
            request.Status,
            cancellationToken);

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

        // 3. (空行后) 映射 DTO 并返回分页结果
        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
    };
}
