using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;

namespace DiunaBI.Infrastructure.Services;

public class GoogleSheetsHelper
{
    public SheetsService? Service { get; private set; }
    private const string ApplicationName = "Diuna";
    private static readonly string[] Scopes = [SheetsService.Scope.Spreadsheets];
    public GoogleSheetsHelper()
    {
        InitializeService();
    }
    private void InitializeService()
    {
        var credential = GetCredentialsFromFile();
        Service = new SheetsService(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.");

        Console.WriteLine($"[GoogleSheetsHelper] Loading credentials from environment variable (length: {json.Length})");

        try
        {
            return GoogleCredential.FromJson(json).CreateScoped(Scopes);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[GoogleSheetsHelper] ERROR: Failed to parse credentials - {ex.Message}");
            throw new InvalidOperationException("Failed to parse Google service account credentials. Ensure GOOGLE_SERVICE_ACCOUNT_JSON is properly formatted.", ex);
        }
#endif
    }
}