using Meziantou.Framework.Win32;

namespace QtCNETAPI.Services
{
    public class CredentialService()
    {
        /*
        
                                   * NOTE *
         This does not work on other platforms such as Linux or macOS. 
         I will probably recode the legacy way of doing this for those other platforms.

        */

        public void SaveAccessToken(string username, string accessToken)
        {
            string applicationName = "QtC.NET";
            if (System.Diagnostics.Debugger.IsAttached) applicationName = "QtC.NET.Development";

            CredentialManager.WriteCredential(applicationName, username, accessToken, $"Access Token For User {username} On QtC.NET", CredentialPersistence.LocalMachine);
        }

        public void DeleteAccessToken()
        {
            string applicationName = "QtC.NET";
            if (System.Diagnostics.Debugger.IsAttached) applicationName = "QtC.NET.Development";

            CredentialManager.DeleteCredential(applicationName);
        }

        public string? GetAccessToken()
        {
            string applicationName = "QtC.NET";
            if (System.Diagnostics.Debugger.IsAttached) applicationName = "QtC.NET.Development";

            var credential = CredentialManager.ReadCredential(applicationName);
            if (credential == null) return null;

            return credential.Password;
        }
    }
}
