using Inventario.Core.Interfaces;
using Inventario.Core.Models;
using Inventario.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace Inventario.Infrastructure.Repositories;

public class InventoryMovementRepository : IInventoryMovementRepository
{
    private readonly AppDbContext _context;

    public InventoryMovementRepository(AppDbContext context)
    {
        _context = context;
    }

    public async Task<IEnumerable<InventoryMovement>> GetAllAsync()
    {
        return await _context.InventoryMovements
            .Include(m => m.Product)
            .OrderByDescending(m => m.CreatedAt)
            .ToListAsync();
    }

    public async Task<IEnumerable<InventoryMovement>> GetByProductIdAsync(int productId)
    {
        return await _context.InventoryMovements
            .Include(m => m.Product)
            .Where(m => m.ProductId == productId)
            .OrderByDescending(m => m.CreatedAt)
            .ToListAsync();
    }

    public async Task<InventoryMovement> AddAsync(InventoryMovement movement)
    {
        _context.InventoryMovements.Add(movement);

        var product = await _context.Products.FindAsync(movement.ProductId)
            ?? throw new InvalidOperationException("Product not found");

        product.Stock += movement.Type == MovementType.Entry ? movement.Quantity : -movement.Quantity;
        product.UpdatedAt = DateTime.UtcNow;

        await _context.SaveChangesAsync();
        return movement;
    }
}
