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

namespace MktXService.Infrastructure.Repositories;

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

    /// <summary>
    /// EN: Unit of work for transaction management.
    /// VI: Unit of work cho quản lý transaction.
    /// </summary>
    public IUnitOfWork UnitOfWork => _context;

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

    /// <inheritdoc/>
    public async Task<Sample?> GetAsync(Guid sampleId)
    {
        var sample = await _context.Samples
            .Include(s => s.Status)
            .FirstOrDefaultAsync(s => s.Id == sampleId);

        return sample;
    }

    /// <inheritdoc/>
    public async Task<IEnumerable<Sample>> GetAllAsync()
    {
        return await _context.Samples
            .Include(s => s.Status)
            .OrderByDescending(s => s.CreatedAt)
            .ToListAsync();
    }

    /// <inheritdoc/>
    public Sample Add(Sample sample)
    {
        return _context.Samples.Add(sample).Entity;
    }

    /// <inheritdoc/>
    public void Update(Sample sample)
    {
        _context.Entry(sample).State = EntityState.Modified;
    }

    /// <inheritdoc/>
    public void Delete(Sample sample)
    {
        _context.Samples.Remove(sample);
    }

    /// <inheritdoc/>
    public async Task<IEnumerable<Sample>> GetByStatusAsync(int statusId)
    {
        return await _context.Samples
            .Include(s => s.Status)
            .Where(s => s.StatusId == statusId)
            .OrderByDescending(s => s.CreatedAt)
            .ToListAsync();
    }
}
