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();

        // 沽清查询不走 Status 过滤，保持“仅沽清”口径。
        var status = request.IsSoldOut == true ? null : request.Status;
        var filter = new ProductSearchFilter
        {
            TenantId = tenantId,
            StoreId = request.StoreId,
            CategoryId = request.CategoryId,
            Status = status,
            Kind = request.Kind,
            Keyword = request.Keyword,
            IsSoldOut = request.IsSoldOut,
            Page = request.Page,
            PageSize = request.PageSize,
            SortBy = request.SortBy,
            SortDescending = request.SortDescending
        };

        var (products, totalCount) = await _productRepository.SearchPagedAsync(filter, cancellationToken);
        var items = products.Select(MapToDto).ToList();
        return new PagedResult<ProductDto>(items, request.Page, request.PageSize, totalCount);
    }

    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,
        Kind = product.Kind,
        SalesMonthly = product.SalesMonthly,
        TagsJson = product.TagsJson,
        SoldoutMode = product.SoldoutMode,
        RecoverAt = product.RecoverAt,
        RemainStock = product.RemainStock,
        SoldoutReason = product.SoldoutReason,
        SyncToPlatform = product.SyncToPlatform,
        NotifyManager = product.NotifyManager,
        TimedOnShelfAt = product.TimedOnShelfAt,
        CoverImage = product.CoverImage,
        GalleryImages = product.GalleryImages,
        Description = product.Description,
        SortWeight = product.SortWeight,
        WarningStock = product.WarningStock,
        PackingFee = product.PackingFee,
        EnableDineIn = product.EnableDineIn,
        EnablePickup = product.EnablePickup,
        EnableDelivery = product.EnableDelivery,
        IsFeatured = product.IsFeatured,
        CreatedAt = product.CreatedAt
    };
}
