#nullable enable
using System;
using System.Threading.Tasks;
using IGP.UnitySDK;
using IGP.UnitySDK.Models;
using UnityEngine;

public sealed class IGPExampleArenaSession : MonoBehaviour
{
    [SerializeField] private IGPRuntimeManager? runtime = null;

    private void Awake()
    {
        runtime ??= FindObjectOfType<IGPRuntimeManager>();
    }

    // Optional. Call these from game-owned UI only when Direct login is wanted.
    public async Task SendPhoneCodeAsync(string phone)
    {
        if (runtime == null)
        {
            throw new InvalidOperationException("IGP Core runtime is unavailable.");
        }

        await runtime.SendPhoneSignInCodeAsync(phone);
    }

    public async Task SignInAsync(string phone, string verificationCode)
    {
        if (runtime == null)
        {
            throw new InvalidOperationException("IGP Core runtime is unavailable.");
        }

        await runtime.SignInWithPhoneCodeAsync(phone, verificationCode);
    }

    public async void RequestArenaSession()
    {
        if (runtime == null)
        {
            return;
        }

        try
        {
            // Direct login needs no Host initialization. Without it, prepare the
            // configured Desktop or Mobile Host before requesting the same API.
            if (!runtime.HasUserSession &&
                !runtime.IsInitialized &&
                !await runtime.InitializeAsync())
            {
                Debug.LogError("IGP Core initialization failed.");
                return;
            }

            IGPArenaSession session = await runtime.RequestArenaSessionAsync();

            // Pass the fields to the caller-owned Gateway client. Never log Token.
            Debug.Log(
                $"Arena session ready for app {session.AppId}, " +
                $"player {session.Player.Id}, expires {session.ExpiresAtUtc:O}.");
        }
        catch (Exception exception)
        {
            Debug.LogError($"Arena session request failed: {exception.Message}");
        }
    }
}
