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

namespace AdsManagerService.Infrastructure.Repositories;

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

    public IUnitOfWork UnitOfWork => _context;

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

    public Campaign Add(Campaign campaign)
    {
        return _context.Campaigns.Add(campaign).Entity;
    }

    public void Update(Campaign campaign)
    {
        _context.Entry(campaign).State = EntityState.Modified;
    }

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

    public async Task<IEnumerable<Campaign>> GetByAdvertiserIdAsync(Guid advertiserId, CancellationToken cancellationToken = default)
    {
        return await _context.Campaigns
            .Where(c => c.AdvertiserId == advertiserId)
            .OrderByDescending(c => c.CreatedAt)
            .ToListAsync(cancellationToken);
    }

    public async Task<IEnumerable<Campaign>> GetActiveAsync(CancellationToken cancellationToken = default)
    {
        return await _context.Campaigns
            .Where(c => c.StatusId == CampaignStatus.Active.Id)
            .ToListAsync(cancellationToken);
    }
}
