import 'dotenv/config';

/**
 * {{AGENT_NAME}} — SentryAgent.ai agent starter
 * Agent ID: {{AGENT_ID}}
 *
 * This file demonstrates how to authenticate with SentryAgent.ai and issue
 * an OAuth2 access token using your agent credentials.
 */

async function main(): Promise<void> {
  const apiUrl = process.env['AGENTIDP_API_URL'] ?? '{{API_URL}}';
  const clientId = process.env['AGENTIDP_CLIENT_ID'] ?? '';
  const clientSecret = process.env['AGENTIDP_CLIENT_SECRET'] ?? '';

  if (!clientId || !clientSecret) {
    console.error('Error: AGENTIDP_CLIENT_ID and AGENTIDP_CLIENT_SECRET must be set in .env');
    process.exit(1);
  }

  console.log(`Issuing token for agent {{AGENT_ID}} at ${apiUrl} ...`);

  const response = await fetch(`${apiUrl}/api/v1/token`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'client_credentials',
      client_id: clientId,
      client_secret: clientSecret,
      scope: 'agents:read',
    }),
  });

  if (!response.ok) {
    const error = await response.text();
    console.error('Token issuance failed:', error);
    process.exit(1);
  }

  const token = await response.json() as { access_token: string; expires_in: number };
  console.log('✓ Token issued successfully!');
  console.log(`  Token type: Bearer`);
  console.log(`  Expires in: ${token.expires_in}s`);
  console.log(`  Token (first 20 chars): ${token.access_token.substring(0, 20)}...`);
}

main().catch((err: unknown) => {
  console.error('Unexpected error:', err);
  process.exit(1);
});
