using Microsoft.EntityFrameworkCore;
using PowderCoating.Core.Entities;
using PowderCoating.Core.Enums;
using PowderCoating.Core.Interfaces.Repositories;
using PowderCoating.Infrastructure.Data;

namespace PowderCoating.Infrastructure.Repositories;

/// <summary>
/// Typed repository for <see cref="InventoryTransaction"/> that adds a dynamic-filter
/// ledger query on top of the generic <see cref="Repository{T}"/>.
/// </summary>
public class InventoryTransactionRepository : Repository<InventoryTransaction>, IInventoryTransactionRepository
{
    public InventoryTransactionRepository(ApplicationDbContext context) : base(context) { }

    /// <inheritdoc/>
    public async Task<List<InventoryTransaction>> GetForLedgerAsync(
        int? itemId,
        DateTime? from,
        DateTime? to,
        InventoryTransactionType? type)
    {
        var query = _context.InventoryTransactions
            .AsNoTracking()
            .Include(t => t.InventoryItem)
            .Include(t => t.PurchaseOrder)
            .Include(t => t.Job)
                .ThenInclude(j => j!.Customer)
            .Where(t => !t.IsDeleted);

        if (itemId.HasValue)
            query = query.Where(t => t.InventoryItemId == itemId.Value);
        if (from.HasValue)
            query = query.Where(t => t.TransactionDate >= from.Value);
        if (to.HasValue)
            query = query.Where(t => t.TransactionDate < to.Value.AddDays(1));
        if (type.HasValue)
            query = query.Where(t => t.TransactionType == type.Value);

        return await query
            .OrderByDescending(t => t.TransactionDate)
            .Take(500)
            .ToListAsync();
    }
}
