using Microsoft.EntityFrameworkCore;
using AdsTrackingService.Domain.AggregatesModel.TrackingPixelAggregate;
using AdsTrackingService.Domain.SeedWork;

namespace AdsTrackingService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for TrackingPixel aggregate.
/// VI: Triển khai repository cho aggregate TrackingPixel.
/// </summary>
public class TrackingPixelRepository : ITrackingPixelRepository
{
    private readonly AdsTrackingServiceContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public TrackingPixelRepository(AdsTrackingServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<TrackingPixel?> GetByAdvertiserIdAsync(Guid advertiserId, CancellationToken ct = default)
    {
        return await _context.TrackingPixels
            .FirstOrDefaultAsync(p => p.AdvertiserId == advertiserId, ct);
    }

    public async Task<TrackingPixel?> GetByPixelCodeAsync(string pixelCode, CancellationToken ct = default)
    {
        return await _context.TrackingPixels
            .FirstOrDefaultAsync(p => p.PixelCode == pixelCode, ct);
    }

    public async Task<IEnumerable<TrackingPixel>> GetActivePixelsAsync(Guid advertiserId, CancellationToken ct = default)
    {
        return await _context.TrackingPixels
            .Where(p => p.AdvertiserId == advertiserId && p.IsActive)
            .ToListAsync(ct);
    }

    public async Task<TrackingPixel?> GetByIdAsync(Guid id, CancellationToken ct = default)
    {
        return await _context.TrackingPixels
            .FindAsync(new object[] { id }, ct);
    }

    public async Task<TrackingPixel> AddAsync(TrackingPixel entity, CancellationToken ct = default)
    {
        return (await _context.TrackingPixels.AddAsync(entity, ct)).Entity;
    }

    public TrackingPixel Update(TrackingPixel entity)
    {
        return _context.TrackingPixels.Update(entity).Entity;
    }

    public void Delete(TrackingPixel entity)
    {
        _context.TrackingPixels.Remove(entity);
    }
}
