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

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 商品选择器查询处理器。
/// </summary>
public sealed class SearchProductPickerQueryHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SearchProductPickerQuery, IReadOnlyList<ProductPickerItemDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<ProductPickerItemDto>> Handle(SearchProductPickerQuery request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var categories = await productRepository.GetCategoriesByStoreAsync(tenantId, request.StoreId, false, cancellationToken);
        var categoryNameLookup = categories.ToDictionary(category => category.Id, category => category.Name);

        var products = await productRepository.SearchPickerAsync(
            tenantId,
            request.StoreId,
            request.CategoryId,
            request.Keyword,
            request.Limit,
            cancellationToken);

        return products
            .Select(product => new ProductPickerItemDto
            {
                Id = product.Id,
                CategoryId = product.CategoryId,
                CategoryName = categoryNameLookup.GetValueOrDefault(product.CategoryId, string.Empty),
                Name = product.Name,
                Price = product.Price,
                SpuCode = product.SpuCode,
                Status = ToPickerStatus(product.Status, product.SoldoutMode.HasValue)
            })
            .ToList();
    }

    private static string ToPickerStatus(ProductStatus status, bool isSoldout)
    {
        if (isSoldout)
        {
            return "sold_out";
        }

        return status switch
        {
            ProductStatus.OnSale => "on_sale",
            _ => "off_shelf"
        };
    }
}
