using Predictalytics.Domain.Entities;
using Predictalytics.Domain.Interfaces;
using Microsoft.EntityFrameworkCore;

namespace Predictalytics.Infrastructure.Data.Repositories;

public class WatchlistRepository : IWatchlistRepository
{
    private readonly AppDbContext _db;
    public WatchlistRepository(AppDbContext db) => _db = db;

    public async Task<IReadOnlyList<WatchlistEntry>> GetAllAsync(CancellationToken ct = default)
        => await _db.WatchlistEntries
            .Include(w => w.Trader)
                .ThenInclude(t => t.Analytics)
            .ToListAsync(ct);

    public async Task<WatchlistEntry?> GetByTraderIdAsync(int traderId, CancellationToken ct = default)
        => await _db.WatchlistEntries.FirstOrDefaultAsync(w => w.TraderId == traderId, ct);

    public async Task AddAsync(WatchlistEntry entry, CancellationToken ct = default)
    { _db.WatchlistEntries.Add(entry); await _db.SaveChangesAsync(ct); }

    public async Task RemoveAsync(int id, CancellationToken ct = default)
    {
        var e = await _db.WatchlistEntries.FindAsync(new object[] { id }, ct);
        if (e != null) { _db.WatchlistEntries.Remove(e); await _db.SaveChangesAsync(ct); }
    }
}
