using Microsoft.EntityFrameworkCore;
using MktXService.Domain.AggregatesModel.SegmentAggregate;
using MktXService.Domain.SeedWork;

namespace MktXService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for Segment aggregate.
/// VI: Triển khai repository cho Segment aggregate.
/// </summary>
public class SegmentRepository : ISegmentRepository
{
    private readonly MktXServiceContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public SegmentRepository(MktXServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public Segment Add(Segment segment)
    {
        return _context.Segments.Add(segment).Entity;
    }

    public void Update(Segment segment)
    {
        _context.Entry(segment).State = EntityState.Modified;
    }

    public void Delete(Segment segment)
    {
        _context.Segments.Remove(segment);
    }

    public async Task<Segment?> GetByIdAsync(Guid id)
    {
        return await _context.Segments.FirstOrDefaultAsync(s => s.Id == id);
    }

    public async Task<Segment?> GetByIdWithConditionsAsync(Guid id)
    {
        return await _context.Segments
            .Include(s => s.Conditions)
            .FirstOrDefaultAsync(s => s.Id == id);
    }

    public async Task<IEnumerable<Segment>> GetByMerchantIdAsync(Guid merchantId)
    {
        return await _context.Segments
            .Include(s => s.Conditions)
            .Where(s => EF.Property<Guid>(s, "_merchantId") == merchantId)
            .OrderByDescending(s => EF.Property<DateTime>(s, "_createdAt"))
            .ToListAsync();
    }

    public async Task<IEnumerable<Segment>> GetByIdsAsync(IEnumerable<Guid> ids)
    {
        return await _context.Segments
            .Include(s => s.Conditions)
            .Where(s => ids.Contains(s.Id))
            .ToListAsync();
    }
}
