// EN: Order repository implementation.
// VI: Implementation repository Order.

using OrderService.Domain.AggregatesModel.OrderAggregate;
using OrderService.Domain.SeedWork;
using Microsoft.EntityFrameworkCore;

namespace OrderService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for Order aggregate.
/// VI: Implementation repository cho Order aggregate.
/// </summary>
public class OrderRepository : IOrderRepository
{
    private readonly OrderContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public OrderRepository(OrderContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public Order Add(Order order)
    {
        return _context.Orders.Add(order).Entity;
    }

    public void Update(Order order)
    {
        _context.Entry(order).State = EntityState.Modified;
    }

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

    public async Task<IEnumerable<Order>> GetByShopIdAsync(Guid shopId, CancellationToken cancellationToken = default)
    {
        return await _context.Orders
            .Where(o => o.ShopId == shopId)
            .OrderByDescending(o => o.CreatedAt)
            .ToListAsync(cancellationToken);
    }

    public async Task<IEnumerable<Order>> GetByCustomerIdAsync(Guid customerId, CancellationToken cancellationToken = default)
    {
        return await _context.Orders
            .Where(o => o.CustomerId == customerId)
            .OrderByDescending(o => o.CreatedAt)
            .ToListAsync(cancellationToken);
    }
}
