import { getSecret, setSecret } from '../../secrets.js';
import { wrapFetch } from '../../egress.js';

export async function getGoogleAccessToken(opts = {}, toolName = 'google_oauth') {
  if (opts.access_token) return opts.access_token;

  const cached = getSecret('GOOGLE_ACCESS_TOKEN', opts);
  if (cached && !opts.force_refresh) return cached;

  const refreshToken = getSecret('GOOGLE_REFRESH_TOKEN', opts);
  const clientId = getSecret('GOOGLE_OAUTH_CLIENT_ID', opts) || process.env.GOOGLE_CLIENT_ID;
  const clientSecret = getSecret('GOOGLE_OAUTH_CLIENT_SECRET', opts) || process.env.GOOGLE_CLIENT_SECRET;
  if (!refreshToken) throw new Error('GOOGLE_REFRESH_TOKEN missing');
  if (!clientId || !clientSecret) throw new Error('GOOGLE_OAUTH_CLIENT_ID/GOOGLE_OAUTH_CLIENT_SECRET missing');

  const body = new URLSearchParams({
    client_id: clientId,
    client_secret: clientSecret,
    refresh_token: refreshToken,
    grant_type: 'refresh_token',
  });
  const loggedFetch = wrapFetch(toolName, opts.agent_id ?? null, opts.fetch || fetch);
  const res = await loggedFetch('https://oauth2.googleapis.com/token', {
    method: 'POST',
    headers: { 'content-type': 'application/x-www-form-urlencoded' },
    body,
  });
  if (!res.ok) throw new Error(`google token refresh failed: ${res.status}`);
  const data = await res.json();
  if (!data.access_token) throw new Error('google token refresh returned no access_token');
  setSecret('GOOGLE_ACCESS_TOKEN', data.access_token, {
    ...opts,
    source: 'oauth_access',
    metadata: { expires_in: data.expires_in || null, refreshed_at: new Date().toISOString() },
  });
  return data.access_token;
}

export function googleFetch(toolName, opts = {}) {
  return wrapFetch(toolName, opts.agent_id ?? null, opts.fetch || fetch);
}
