/**
 * @description Grubtech API Authentication - TypeScript
 * @author Grubtech Integration Team
 * @version 1.0.0
 *
 * This example demonstrates how to authenticate with the Grubtech API
 * using an API key to obtain an access token.
 *
 * Prerequisites:
 * - Node.js 18+ with fetch API support
 * - Valid Grubtech API key
 *
 * Replace the following placeholders:
 * - {{API_KEY}}: Your Grubtech API key
 * - {{PARTNER_ID}}: Your partner identifier
 */

const API_KEY = '{{API_KEY}}';
const PARTNER_ID = '{{PARTNER_ID}}';
const BASE_URL = 'https://api.staging.grubtech.io';

interface AuthResponse {
  token: string;
  expiresIn: number;
  tokenType: string;
}

/**
 * Authenticate with Grubtech API and obtain access token
 */
async function authenticate(): Promise<string> {
  try {
    // Construct authentication request
    const response = await fetch(`${BASE_URL}/v1/auth/token`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': API_KEY,
      },
      body: JSON.stringify({
        partnerId: PARTNER_ID,
        grantType: 'api_key',
      }),
    });

    // Check for errors
    if (!response.ok) {
      const errorBody = await response.text();
      throw new Error(
        `Authentication failed: ${response.status} - ${errorBody}`
      );
    }

    // Extract token from response
    const data: AuthResponse = await response.json();
    const token = data.token;

    console.log('Authentication successful!');
    console.log(`Token expires in: ${data.expiresIn} seconds`);

    return token;
  } catch (error) {
    console.error('Authentication error:', error);
    throw error;
  }
}

/**
 * Example: Use token in subsequent API requests
 */
async function exampleApiCall(token: string) {
  const response = await fetch(`${BASE_URL}/v1/menus`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    throw new Error(`API call failed: ${response.status}`);
  }

  return response.json();
}

// Main execution
(async () => {
  try {
    const token = await authenticate();

    // Use token for API calls
    const menus = await exampleApiCall(token);
    console.log('Menus:', menus);
  } catch (error) {
    process.exit(1);
  }
})();
