// Copyright (c) 2026 EzAdmin. All rights reserved.
// Licensed under the EzAdmin Client License. See LICENSE-CLIENT.txt.

using System;
using UnityEngine;

namespace EzAdmin.Client
{
    internal static class EzAdminAttestation
    {
        internal static bool Available
        {
#if EZADMIN_META_PLATFORM && UNITY_ANDROID && !UNITY_EDITOR
            get { return true; }
#else
            get { return false; }
#endif
        }

        internal static void Request(string nonce, Action<string, string> done)
        {
#if EZADMIN_META_PLATFORM && UNITY_ANDROID && !UNITY_EDITOR
            try
            {
                if (Application.internetReachability == NetworkReachability.NotReachable)
                {
                    done(null, "no internet");
                    return;
                }
                if (!Oculus.Platform.Core.IsInitialized())
                    Oculus.Platform.Core.AsyncInitialize();
                var request = Oculus.Platform.DeviceApplicationIntegrity.GetIntegrityToken(nonce);
                if (request == null)
                {
                    done(null, "the Meta Platform SDK is not set up");
                    return;
                }
                request.OnComplete(message =>
                {
                    if (message == null || message.IsError)
                    {
                        string why = message != null && message.GetError() != null ? message.GetError().Message : "";
                        done(null, string.IsNullOrEmpty(why) ? "Meta did not answer" : why);
                    }
                    else
                    {
                        done(message.Data, null);
                    }
                });
            }
            catch (Exception e)
            {
                done(null, e.GetType().Name);
            }
#else
            done(null, null);
#endif
        }
    }
}
