using System;
using System.Threading;
using Cysharp.Threading.Tasks;
using UnityEngine;
using VContainer.Unity;

namespace QuizPleaseTest.Boot.Flow
{
    public class BootstrapEntryPoint : IStartable, IDisposable
    {
        private readonly IBootFlowService _bootFlowService;
        private CancellationTokenSource _lifetimeCts;

        public BootstrapEntryPoint(IBootFlowService bootFlowService)
        {
            _bootFlowService = bootFlowService;
        }

        public void Start()
        {
            _lifetimeCts = new CancellationTokenSource();
            RunAsync(_lifetimeCts.Token).Forget();
        }

        public void Dispose()
        {
            if (_lifetimeCts == null)
            {
                return;
            }

            _lifetimeCts.Cancel();
            _bootFlowService.ReleaseAsync(CancellationToken.None).Forget();
            _lifetimeCts.Dispose();
            _lifetimeCts = null;
        }

        private async UniTask RunAsync(CancellationToken ct)
        {
            try
            {
                await _bootFlowService.InitializeAsync(ct);
            }
            catch (OperationCanceledException) when (ct.IsCancellationRequested)
            {
            }
            catch (Exception exception)
            {
                Debug.LogException(exception);
            }
        }
    }
}
