/**
 * Authentication manager
 * Automatically selects between OAuth and Service Account based on environment
 */

import type { OAuth2Client } from 'google-auth-library';
import type { JWT } from 'google-auth-library';
import { getOAuthClient, loadOAuthConfig } from './oauth.js';
import { getServiceAccountClient, loadServiceAccountConfig } from './service-account.js';

export type AuthClient = OAuth2Client | JWT;

/**
 * Get authenticated client, automatically choosing auth method
 * Priority: OAuth > Service Account
 */
export async function getAuthClient(): Promise<AuthClient> {
  // Try OAuth first (better for interactive use)
  const oauthConfig = loadOAuthConfig();
  if (oauthConfig) {
    console.error('Using OAuth 2.0 authentication');
    return await getOAuthClient();
  }

  // Fall back to service account
  const serviceAccountConfig = loadServiceAccountConfig();
  if (serviceAccountConfig) {
    console.error('Using Service Account authentication');
    return getServiceAccountClient();
  }

  // No auth configured
  throw new Error(`
No authentication configured. Please set one of:
  - OAuth: GSC_OAUTH_CLIENT_ID + GSC_OAUTH_CLIENT_SECRET
  - OAuth file: GSC_OAUTH_CLIENT_FILE=/path/to/client_secrets.json
  - Service Account: GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
  - Service Account key: GSC_SERVICE_ACCOUNT_KEY=base64encodedkey
  `.trim());
}

export { getOAuthClient } from './oauth.js';
export { getServiceAccountClient } from './service-account.js';
