using AdsManagerService.Domain.AggregatesModel.AdSetAggregate;
using AdsManagerService.Domain.SeedWork;
using Microsoft.EntityFrameworkCore;

namespace AdsManagerService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for AdSet aggregate.
/// VI: Triển khai repository cho AdSet aggregate.
/// </summary>
public class AdSetRepository : IAdSetRepository
{
    private readonly AdsManagerServiceContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public AdSetRepository(AdsManagerServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public AdSet Add(AdSet adSet)
    {
        return _context.AdSets.Add(adSet).Entity;
    }

    public void Update(AdSet adSet)
    {
        _context.Entry(adSet).State = EntityState.Modified;
    }

    public async Task<AdSet?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
    {
        return await _context.AdSets
            .FirstOrDefaultAsync(a => a.Id == id, cancellationToken);
    }

    public async Task<IEnumerable<AdSet>> GetByCampaignIdAsync(Guid campaignId, CancellationToken cancellationToken = default)
    {
        return await _context.AdSets
            .Where(a => a.CampaignId == campaignId)
            .OrderByDescending(a => a.CreatedAt)
            .ToListAsync(cancellationToken);
    }
}
