using MediatR;
using TakeoutSaaS.Application.App.Coupons.Seckill.Dto;
using TakeoutSaaS.Application.App.Coupons.Seckill.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.Seckill.Handlers;

/// <summary>
/// 秒杀活动列表查询处理器。
/// </summary>
public sealed class GetSeckillCampaignListQueryHandler(
    IPromotionCampaignRepository promotionCampaignRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetSeckillCampaignListQuery, SeckillListResultDto>
{
    /// <inheritdoc />
    public async Task<SeckillListResultDto> Handle(GetSeckillCampaignListQuery request, CancellationToken cancellationToken)
    {
        var page = Math.Max(1, request.Page);
        var pageSize = Math.Clamp(request.PageSize, 1, 200);

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

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

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

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

        var nowUtc = DateTime.UtcNow;

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

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

        var stats = SeckillDtoFactory.ToStatsDto(visibleItems);

        IEnumerable<SeckillListItemDto> 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 SeckillListResultDto
        {
            Items = paged,
            TotalCount = total,
            Page = page,
            PageSize = pageSize,
            Stats = stats
        };
    }
}


