using JasperFx.Core.Reflection;
using Microsoft.EntityFrameworkCore;
using Monitoring.Infrastructure.Data;
using Monitoring.Models;
using Monitoring.Services;
using Serilog;

namespace Monitoring.DomainEvents.EventCreated.Handlers;

public sealed class NotifyOperatorsHandler
{
	public async Task Handle(
		EventCreatedDomainEvent eventEntity,
		IDataContext dataContext,
		INotificationService notificationService,
		UsersService usersService,
		CancellationToken cancellationToken
	)
	{
		Log.Information("Try to notify operators for event with Id = {Id}", eventEntity.Id);

		var model = await dataContext
			.Events.Where(x => x.Id == eventEntity.Id)
			.Select(EventModel.FromEntity)
			.FirstOrDefaultAsync(cancellationToken);
		if (model is null)
		{
			return;
		}

		var userIds = await usersService.GetWatcherIdListByAsset(
			new(model.AssetId),
			cancellationToken
		);
		if (!userIds.Any())
		{
			return;
		}

		await notificationService.NotifyUsers(userIds, "EVENTS.CREATED", model, cancellationToken);

		Log.Information(
			"Notified {Count} operators for event with Id = {Id}",
			userIds.Count(),
			eventEntity.Id
		);
	}
}
