# Register Game Example

To interact with the play.fun API, you first need to generate an HMAC signature. This is done using your **API key** and **secret key**, along with the request path and method. The generated signature is then used to authenticate subsequent API requests, such as registering a new game on the platform. The following example demonstrates how to request a signature from the play.fun API and then use it to securely register your game or game's built by developers on your platform.

```typescript
/**
 * Generates HMAC signature for API authentication
 * @returns {Promise<string>} The signature for API requests
 */
async function getSignature() {
  try {
    const response = await fetch(`https://api.play.fun/user/hmac-signature`, {
      method: 'POST',
      body: JSON.stringify({
        secretKey: SECRET_KEY,
        path: '/games',
        method: 'POST',
        apiKey: API_KEY,
      }),
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error(`Failed to get signature: ${response.status} ${response.statusText}`);
    }

    const result = await response.json();
    return result.data.signature;
  } catch (error) {
    console.error('Failed to get signature:', error);
    throw new Error('Signature generation failed');
  }
}

/**
 * Registers a game with the OGP platform
 * @param {Object} gameData - Game registration data
 * @returns {Promise<Object>} Registration result with game API key
 */
async function registerGame(gameData) {
  const signature = await getSignature();

  if (
    !gameData.name ||
    !gameData.image ||
    !gameData.gameUrl ||
    !gameData.isHTMLGame ||
    !gameData.tokens ||
    gameData.tokens.length === 0
  ) {
    throw new Error('Missing required fields');
  }

  const payload = {
    name: gameData.name,
    description: gameData.description || undefined,
    gameUrl: formatUrl(gameData.gameUrl),
    image: gameData.image,
    platform: 'web',
    isHTMLGame: gameData.isHTMLGame,
    tokens: gameData.tokens,
    // Set hidden to true to deploy without appearing in public listings.
    // Useful for testing play.fun integrations before making the game public.
    hidden: gameData.hidden || false,
  };

  // Add optional fields if provided
  if (gameData.developers && gameData.developers.length > 0) {
    payload.developers = gameData.developers;
  }
  if (gameData.coverImage) {
    payload.coverImage = gameData.coverImage;
  }
  if (gameData.twitter) {
    payload.twitter = formatUrl(gameData.twitter, 'https://twitter.com/');
  }
  if (gameData.discord) {
    payload.discord = formatUrl(gameData.discord, 'https://discord.gg/');
  }

  console.log('Submitting game registration:', payload);

  const response = await fetch(`https://api.play.fun/games`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      'x-auth-provider': 'hmac',
      Authorization: signature,
    },
    body: JSON.stringify(payload),
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(
      `Registration failed: ${response.status} ${response.statusText} - ${errorText}`,
    );
  }

  const result = await response.json();
  console.log('Registration response:', result);

  if (result.data && result.data.gameApiKey) {
    return {
      success: true,
      game: { apiKey: result.data.gameApiKey },
      uploads: result.data.uploads || {},
    };
  } else {
    throw new Error('Registration failed: No gameApiKey returned.');
  }
}
```
