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 EfPromotionCampaignRepository(TakeoutAppDbContext context) : IPromotionCampaignRepository
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<PromotionCampaign>> GetByPromotionTypeAsync(
        long tenantId,
        PromotionType promotionType,
        CancellationToken cancellationToken = default)
    {
        return await context.PromotionCampaigns
            .AsNoTracking()
            .Where(x => x.TenantId == tenantId && x.PromotionType == promotionType)
            .OrderByDescending(x => x.UpdatedAt ?? x.CreatedAt)
            .ThenByDescending(x => x.Id)
            .ToListAsync(cancellationToken);
    }

    /// <inheritdoc />
    public Task<PromotionCampaign?> FindByIdAsync(
        long campaignId,
        long tenantId,
        PromotionType promotionType,
        CancellationToken cancellationToken = default)
    {
        return context.PromotionCampaigns
            .Where(x => x.TenantId == tenantId && x.PromotionType == promotionType && x.Id == campaignId)
            .FirstOrDefaultAsync(cancellationToken);
    }

    /// <inheritdoc />
    public Task AddAsync(PromotionCampaign campaign, CancellationToken cancellationToken = default)
    {
        return context.PromotionCampaigns.AddAsync(campaign, cancellationToken).AsTask();
    }

    /// <inheritdoc />
    public Task UpdateAsync(PromotionCampaign campaign, CancellationToken cancellationToken = default)
    {
        context.PromotionCampaigns.Update(campaign);
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task DeleteAsync(PromotionCampaign campaign, CancellationToken cancellationToken = default)
    {
        context.PromotionCampaigns.Remove(campaign);
        return Task.CompletedTask;
    }

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