namespace WalletService.Infrastructure.Repositories;

using Microsoft.EntityFrameworkCore;
using WalletService.Domain.AggregatesModel.PaymentAggregate;
using WalletService.Domain.SeedWork;

/// <summary>
/// EN: Repository implementation for Payment aggregate.
/// VI: Repository implementation cho aggregate Payment.
/// </summary>
public class PaymentRepository : IPaymentRepository
{
    private readonly WalletServiceContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public PaymentRepository(WalletServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    /// <inheritdoc />
    public async Task<Payment?> GetByIdAsync(Guid paymentId)
    {
        return await _context.Payments
            .FirstOrDefaultAsync(p => p.Id == paymentId);
    }

    /// <inheritdoc />
    public async Task<Payment?> GetByOrderIdAsync(Guid orderId)
    {
        return await _context.Payments
            .OrderByDescending(p => p.CreatedAt)
            .FirstOrDefaultAsync(p => p.OrderId == orderId);
    }

    /// <inheritdoc />
    public async Task<Payment?> GetByTransactionIdAsync(string transactionId)
    {
        return await _context.Payments
            .FirstOrDefaultAsync(p => p.TransactionId == transactionId);
    }

    /// <inheritdoc />
    public async Task<IEnumerable<Payment>> GetPaymentsByOrderIdAsync(Guid orderId)
    {
        return await _context.Payments
            .Where(p => p.OrderId == orderId)
            .OrderByDescending(p => p.CreatedAt)
            .ToListAsync();
    }

    /// <inheritdoc />
    public Payment Add(Payment payment)
    {
        return _context.Payments.Add(payment).Entity;
    }

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