import { config as dotenvConfig } from 'dotenv';
import { GoogleAuth } from 'google-auth-library';
import { google } from 'googleapis';
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
/** Initialize the Google Sheets API client from base64-encoded service account credentials in `GOOGLE_SERVICE_ACCOUNT`. */
export async function initializeSheetsApi() {
    dotenvConfig();
    const base64Credentials = process.env.GOOGLE_SERVICE_ACCOUNT;
    if (!base64Credentials) {
        throw new Error('Missing GOOGLE_SERVICE_ACCOUNT environment variable.\n' +
            'Set it with: base64 -i service-account.json and paste in .env\n' +
            'Then run: aurora env decrypt (if using SOPS)');
    }
    const credentials = JSON.parse(Buffer.from(base64Credentials, 'base64').toString());
    const auth = new GoogleAuth({
        credentials,
        scopes: SCOPES,
    });
    return google.sheets({ auth, version: 'v4' });
}
/** Test connection to a spreadsheet by fetching its title. */
export async function testConnection(sheetsApi, spreadsheetId) {
    try {
        await sheetsApi.spreadsheets.get({
            fields: 'properties.title',
            spreadsheetId,
        });
        return true;
    }
    catch (error) {
        const err = error;
        if (err.message.includes('403')) {
            throw new Error(`Access denied to spreadsheet ${spreadsheetId}. ` +
                'Make sure you shared the spreadsheet with the service account email.');
        }
        throw error;
    }
}
