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

using PlayFab;
using PlayFab.ClientModels;
using UnityEngine;

namespace EzAdmin.Client
{

    [DisallowMultipleComponent]
    public sealed class EzAdminAutoLogin : MonoBehaviour
    {
        [Tooltip("Make a PlayFab account for this device the first time it is seen.")]
        [SerializeField] private bool _createAccount = true;

        [Tooltip("Print what happens to the Console.")]
        [SerializeField] private bool _log = true;

        public static bool IsSignedIn => PlayFabClientAPI.IsClientLoggedIn();

        private void Start()
        {
            if (PlayFabClientAPI.IsClientLoggedIn())
            {
                return;
            }
            if (string.IsNullOrEmpty(PlayFabSettings.staticSettings.TitleId))
            {
                Debug.LogError("EzAdminAutoLogin: no PlayFab Title ID. Put yours in PlayFabSharedSettings " +
                               "(search the Project window for it).", this);
                return;
            }

            PlayFabClientAPI.LoginWithCustomID(new LoginWithCustomIDRequest
            {
                CustomId = SystemInfo.deviceUniqueIdentifier,
                CreateAccount = _createAccount
            }, result =>
            {
                if (_log) Debug.Log("EzAdmin: signed in to PlayFab as " + result.PlayFabId);
            }, error =>
            {
                Debug.LogWarning("EzAdmin: PlayFab sign-in failed: " + error.GenerateErrorReport(), this);
            });
        }
    }
}
