using MediatR;
using TakeoutSaaS.Application.App.Coupons.FlashSale.Dto;
using TakeoutSaaS.Application.App.Coupons.FlashSale.Queries;
using TakeoutSaaS.Domain.Coupons.Enums;
using TakeoutSaaS.Domain.Coupons.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Coupons.FlashSale.Handlers;

/// <summary>
/// 限时折扣活动列表查询处理器。
/// </summary>
public sealed class GetFlashSaleCampaignListQueryHandler(
    IPromotionCampaignRepository promotionCampaignRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetFlashSaleCampaignListQuery, FlashSaleListResultDto>
{
    /// <inheritdoc />
    public async Task<FlashSaleListResultDto> Handle(GetFlashSaleCampaignListQuery request, CancellationToken cancellationToken)
    {
        var page = Math.Max(1, request.Page);
        var pageSize = Math.Clamp(request.PageSize, 1, 200);

        if (!FlashSaleMapping.TryNormalizeDisplayStatusFilter(request.Status, out var normalizedStatus))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法");
        }

        if (request.VisibleStoreIds.Count == 0)
        {
            return new FlashSaleListResultDto
            {
                Items = [],
                TotalCount = 0,
                Page = page,
                PageSize = pageSize,
                Stats = new FlashSaleStatsDto()
            };
        }

        var tenantId = tenantProvider.GetCurrentTenantId();
        var campaigns = await promotionCampaignRepository.GetByPromotionTypeAsync(
            tenantId,
            PromotionType.FlashSale,
            cancellationToken);

        if (campaigns.Count == 0)
        {
            return new FlashSaleListResultDto
            {
                Items = [],
                TotalCount = 0,
                Page = page,
                PageSize = pageSize,
                Stats = new FlashSaleStatsDto()
            };
        }

        var nowUtc = DateTime.UtcNow;

        var visibleItems = new List<FlashSaleListItemDto>(campaigns.Count);
        foreach (var campaign in campaigns)
        {
            var rules = FlashSaleMapping.DeserializeRules(campaign.RulesJson, campaign.Id);
            if (!FlashSaleMapping.HasVisibleStore(rules, request.VisibleStoreIds))
            {
                continue;
            }

            visibleItems.Add(FlashSaleDtoFactory.ToListItemDto(campaign, rules, nowUtc));
        }

        var stats = FlashSaleDtoFactory.ToStatsDto(visibleItems);

        IEnumerable<FlashSaleListItemDto> filtered = visibleItems;
        if (!string.IsNullOrWhiteSpace(normalizedStatus))
        {
            filtered = filtered.Where(item =>
                string.Equals(item.DisplayStatus, normalizedStatus, StringComparison.Ordinal));
        }

        var keyword = request.Keyword?.Trim();
        if (!string.IsNullOrWhiteSpace(keyword))
        {
            filtered = filtered.Where(item =>
                item.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase));
        }

        var ordered = filtered
            .OrderByDescending(item => item.UpdatedAt)
            .ThenByDescending(item => item.Id)
            .ToList();

        var total = ordered.Count;
        var paged = ordered
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToList();

        return new FlashSaleListResultDto
        {
            Items = paged,
            TotalCount = total,
            Page = page,
            PageSize = pageSize,
            Stats = stats
        };
    }
}

