using Microsoft.Extensions.Hosting;

using Serilog;

using Telegram.Bot;

namespace TelegramSender;
internal class SendJob(
	TelegramSenderOptions options,
	MessageHub messageHub
) : BackgroundService
{
	private TelegramBotClient? _client;

	protected override async Task ExecuteAsync(CancellationToken stoppingToken)
	{
		_ = await Initialize(stoppingToken);

		while (!stoppingToken.IsCancellationRequested)
		{
			await Attempt(stoppingToken);
			await Task.Delay(1000, stoppingToken);
		}
	}

	private async Task Attempt(CancellationToken cancellationToken)
	{
		try
		{
			if (_client is null)
			{
				return;
			}

			for (var i = 0; i < options.BatchSize; i++)
			{
				if (!messageHub.TryDequeue(out var message))
				{
					break;
				}

				await Send(_client, message, cancellationToken);
			}
		}
		catch (Exception ex)
		{
			Log.Error(ex, "{Sender}: Failed to send message", nameof(SendJob));
		}
	}

	private async Task Send(
		TelegramBotClient client,
		string message,
		CancellationToken cancellationToken)
	{
		await client.SendMessage(
			options.ChatId,
			message,
			cancellationToken: cancellationToken);
	}

	private async Task<bool> Initialize(CancellationToken cancellationToken)
	{
		try
		{
			_client = new TelegramBotClient(options.Token);
			var me = await _client.GetMe(cancellationToken);

			//_client.OnMessage += async (message, updateType) =>
			//{
			//	switch (updateType)
			//	{
			//		case Telegram.Bot.Types.Enums.UpdateType.Message:
			//			var chat = message.Chat.Id;
			//			break;
			//	}				
			//};


			Log.Information("Telegram bot {BotId} started", me.Id);

			return true;
		}
		catch (Exception ex)
		{
			Log.Error(ex, "Failed to initialize Telegram bot");

			return false;
		}
	}
}
