using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DiunaBI.Infrastructure.Services;

public class GoogleDriveHelper
{
    public DriveService? Service { get; private set; }
    private const string ApplicationName = "Diuna";
    private static readonly string[] Scopes = [DriveService.Scope.Drive];
    public GoogleDriveHelper()
    {
        InitializeService();
    }
    private void InitializeService()
    {
        var credential = GetCredentialsFromFile();
        Service = new DriveService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName
        });
    }
    private static GoogleCredential GetCredentialsFromFile()
    {
#if DEBUG
        using var stream = new FileStream("client_secrets.Development.json", FileMode.Open, FileAccess.Read);
        return GoogleCredential.FromStream(stream).CreateScoped(Scopes);
#else
        var json = Environment.GetEnvironmentVariable("GOOGLE_SERVICE_ACCOUNT_JSON");
        if (string.IsNullOrWhiteSpace(json))
            throw new InvalidOperationException("GOOGLE_SERVICE_ACCOUNT_JSON environment variable is not set.");
        json = json.Replace("\\n", "\n");
        return GoogleCredential.FromJson(json).CreateScoped(Scopes);
#endif
    }
}