using Dapper;
using SIGCM.Domain.Entities;
using SIGCM.Infrastructure.Data;

namespace SIGCM.Infrastructure.Repositories;

public class NotificationRepository
{
  private readonly IDbConnectionFactory _db;
  public NotificationRepository(IDbConnectionFactory db) => _db = db;

  public async Task<IEnumerable<Notification>> GetByUserAsync(int userId)
  {
    using var conn = _db.CreateConnection();
    return await conn.QueryAsync<Notification>(
        "SELECT TOP 10 * FROM Notifications WHERE UserId = @userId ORDER BY CreatedAt DESC",
        new { userId });
  }

  public async Task MarkAsReadAsync(int notificationId)
  {
    using var conn = _db.CreateConnection();
    await conn.ExecuteAsync("UPDATE Notifications SET IsRead = 1 WHERE Id = @Id", new { Id = notificationId });
  }

  public async Task<int> GetUnreadCountAsync(int userId)
  {
    using var conn = _db.CreateConnection();
    return await conn.ExecuteScalarAsync<int>(
        "SELECT COUNT(1) FROM Notifications WHERE UserId = @userId AND IsRead = 0",
        new { userId });
  }
}