using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Monitoring.Common;
using Monitoring.Infrastructure.Data;
using Monitoring.Services;
using Ping.Models;

namespace Ping.Job;

public class PingJob(
	DataContext dataContext,
	INotificationService notificationService,
	IOptions<AppSettings> options,
	ILogger<PingJob> logger
) : BackgroundService
{
	private const string METHOD = "PING";

	protected override async Task ExecuteAsync(CancellationToken stoppingToken)
	{
		while (!stoppingToken.IsCancellationRequested)
		{
			try
			{
				logger.LogInformation("PING message sending");

				var userIdList = await dataContext
					.Users.Where(user => user.Role.Name == Roles.Watcher)
					.Select(user => user.Id)
					.ToListAsync(stoppingToken);

				logger.LogInformation("Found {Count} watchers to notify", userIdList.Count);

				await notificationService.NotifyUsers(userIdList, METHOD, new { }, stoppingToken);
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "Ошибка при проверке статуса PING");
			}

			await Task.Delay(options.Value.IntervalInSeconds * 1000, stoppingToken);
		}
	}
}
