using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.Coupons.Entities;
using TakeoutSaaS.Domain.Coupons.Enums;
using TakeoutSaaS.Domain.Coupons.Repositories;
using TakeoutSaaS.Infrastructure.App.Persistence;

namespace TakeoutSaaS.Infrastructure.App.Repositories;

/// <summary>
/// 优惠券聚合的 EF Core 仓储实现。
/// </summary>
public sealed class EfCouponRepository(TakeoutAppDbContext context) : ICouponRepository
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<CouponTemplate>> GetTemplatesAsync(long tenantId, CancellationToken cancellationToken = default)
    {
        return await context.CouponTemplates
            .AsNoTracking()
            .Where(x => x.TenantId == tenantId)
            .OrderByDescending(x => x.UpdatedAt ?? x.CreatedAt)
            .ThenByDescending(x => x.Id)
            .ToListAsync(cancellationToken);
    }

    /// <inheritdoc />
    public Task<CouponTemplate?> FindTemplateByIdAsync(long templateId, long tenantId, CancellationToken cancellationToken = default)
    {
        return context.CouponTemplates
            .Where(x => x.TenantId == tenantId && x.Id == templateId)
            .FirstOrDefaultAsync(cancellationToken);
    }

    /// <inheritdoc />
    public Task AddTemplateAsync(CouponTemplate template, CancellationToken cancellationToken = default)
    {
        return context.CouponTemplates.AddAsync(template, cancellationToken).AsTask();
    }

    /// <inheritdoc />
    public Task UpdateTemplateAsync(CouponTemplate template, CancellationToken cancellationToken = default)
    {
        context.CouponTemplates.Update(template);
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task DeleteTemplateAsync(CouponTemplate template, CancellationToken cancellationToken = default)
    {
        context.CouponTemplates.Remove(template);
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task<int> CountIssuedCouponsByTemplateIdAsync(long tenantId, long templateId, CancellationToken cancellationToken = default)
    {
        return context.Coupons
            .AsNoTracking()
            .Where(x => x.TenantId == tenantId && x.CouponTemplateId == templateId)
            .CountAsync(cancellationToken);
    }

    /// <inheritdoc />
    public async Task<Dictionary<long, int>> CountRedeemedCouponsByTemplateIdsAsync(
        long tenantId,
        IReadOnlyCollection<long> templateIds,
        CancellationToken cancellationToken = default)
    {
        if (templateIds.Count == 0)
        {
            return [];
        }

        return await context.Coupons
            .AsNoTracking()
            .Where(x =>
                x.TenantId == tenantId &&
                templateIds.Contains(x.CouponTemplateId) &&
                x.Status == CouponStatus.Redeemed)
            .GroupBy(x => x.CouponTemplateId)
            .Select(group => new { CouponTemplateId = group.Key, Count = group.Count() })
            .ToDictionaryAsync(item => item.CouponTemplateId, item => item.Count, cancellationToken);
    }

    /// <inheritdoc />
    public Task SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        return context.SaveChangesAsync(cancellationToken);
    }
}
