/**
 * Service Account authentication for Google Search Console
 * Used for automated/CI environments
 */

import { JWT } from 'google-auth-library';
import { readFileSync } from 'fs';

const SCOPES = [
  'https://www.googleapis.com/auth/webmasters',
  'https://www.googleapis.com/auth/webmasters.readonly',
  'https://www.googleapis.com/auth/indexing'
];

export interface ServiceAccountConfig {
  type: string;
  project_id: string;
  private_key_id: string;
  private_key: string;
  client_email: string;
  client_id: string;
  auth_uri: string;
  token_uri: string;
  auth_provider_x509_cert_url: string;
  client_x509_cert_url: string;
}

/**
 * Load service account credentials from environment or file
 */
export function loadServiceAccountConfig(): ServiceAccountConfig | null {
  // Try GOOGLE_APPLICATION_CREDENTIALS (standard Google Cloud env var)
  if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
    try {
      const content = readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS, 'utf-8');
      return JSON.parse(content);
    } catch (error: any) {
      throw new Error(
        `Failed to load service account from GOOGLE_APPLICATION_CREDENTIALS: ${error.message}`
      );
    }
  }

  // Try GSC_SERVICE_ACCOUNT_KEY (base64 encoded JSON)
  if (process.env.GSC_SERVICE_ACCOUNT_KEY) {
    try {
      const decoded = Buffer.from(process.env.GSC_SERVICE_ACCOUNT_KEY, 'base64').toString('utf-8');
      return JSON.parse(decoded);
    } catch (error: any) {
      throw new Error(
        `Failed to decode GSC_SERVICE_ACCOUNT_KEY: ${error.message}`
      );
    }
  }

  return null;
}

/**
 * Create authenticated JWT client from service account
 */
export function getServiceAccountClient(): JWT {
  const config = loadServiceAccountConfig();
  
  if (!config) {
    throw new Error(
      'Service account credentials not found. Set GOOGLE_APPLICATION_CREDENTIALS or GSC_SERVICE_ACCOUNT_KEY'
    );
  }

  const client = new JWT({
    email: config.client_email,
    key: config.private_key,
    scopes: SCOPES
  });

  return client;
}
