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

namespace Predictalytics.Infrastructure.Data.Repositories;

public class AlertRepository : IAlertRepository
{
    private readonly AppDbContext _db;
    public AlertRepository(AppDbContext db) => _db = db;

    public async Task<IReadOnlyList<Alert>> GetRecentAsync(int count = 50, bool unreadOnly = false, CancellationToken ct = default)
    {
        var q = _db.Alerts.AsQueryable();
        if (unreadOnly) q = q.Where(a => !a.IsRead);
        return await q.OrderByDescending(a => a.CreatedAt).Take(count).ToListAsync(ct);
    }

    public async Task AddAsync(Alert alert, CancellationToken ct = default)
    { _db.Alerts.Add(alert); await _db.SaveChangesAsync(ct); }

    public async Task MarkAsReadAsync(int id, CancellationToken ct = default)
    {
        var a = await _db.Alerts.FindAsync(new object[] { id }, ct);
        if (a != null) { a.IsRead = true; await _db.SaveChangesAsync(ct); }
    }

    public async Task<int> GetUnreadCountAsync(CancellationToken ct = default)
        => await _db.Alerts.CountAsync(a => !a.IsRead, ct);
}
