using Managing.Application.Abstractions.Grains;
using Microsoft.Extensions.Hosting;
using static Managing.Common.Enums;

namespace Managing.Application.Grains;

public class GrainInitializer : IHostedService
{
    private readonly IGrainFactory _grainFactory;

    public GrainInitializer(IClusterClient grainFactory)
    {
        _grainFactory = grainFactory;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        await InitializePriceFetcherAsync();
        await InitializeBotRemindersAsync();
    }

    public async Task InitializeBotRemindersAsync()
    {
        if (Environment.GetEnvironmentVariable("TASK_SLOT") != "1")
            return;

        var grain = _grainFactory.GetGrain<IBotReminderInitializerGrain>(0);
        await grain.InitializeBotRemindersAsync();
    }

    public async Task InitializePriceFetcherAsync()
    {
        if (Environment.GetEnvironmentVariable("TASK_SLOT") != "1")
            return;

        // Initialize grains for different timeframes
        var timeframes = new[]
        {
            Timeframe.FiveMinutes,
            Timeframe.FifteenMinutes,
            Timeframe.OneHour,
            Timeframe.FourHour,
            Timeframe.OneDay
        };

        foreach (var timeframe in timeframes)
        {
            var grain = _grainFactory.GetGrain<IPriceFetcherGrain>(timeframe.ToString());
            Console.WriteLine("Init grain for {0}: {1}", timeframe, grain.GetGrainId());

            // Actually call a method on the grain to activate it
            // This will trigger OnActivateAsync and register the reminder
            await grain.FetchAndPublishPricesAsync();

            Console.WriteLine("PriceFetcherGrain for {0} activated and initial fetch completed", timeframe);
        }
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}