using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace MadByteLabs.__PRODUCT__.SceneLoader
{
    /// <summary>
    /// Loads scenes on the Unity main thread using caller-owned coroutines. Unity scene loads cannot be cancelled;
    /// stopping the caller's coroutine stops observation only, not the underlying operation.
    /// </summary>
    public sealed class SceneLoader
    {
        /// <summary>Loads a configured scene and yields until completion; invalid scenes fail explicitly.</summary>
        /// <param name="scenePath">Full scene asset path included in the active build profile.</param>
        /// <param name="mode">Whether to replace or add scenes.</param>
        /// <returns>A caller-owned enumerator observing the load operation.</returns>
        public IEnumerator Load(string scenePath, LoadSceneMode mode)
        {
            if (string.IsNullOrWhiteSpace(scenePath))
            {
                throw new ArgumentException("A scene path is required.", nameof(scenePath));
            }

            if (!Application.CanStreamedLevelBeLoaded(scenePath))
            {
                throw new ArgumentException("Scene is unavailable in the active build profile: " + scenePath,
                    nameof(scenePath));
            }

            AsyncOperation operation = SceneManager.LoadSceneAsync(scenePath, mode);
            if (operation == null)
            {
                throw new InvalidOperationException("Unity could not start loading scene: " + scenePath);
            }

            yield return operation;
        }
    }
}
