#!/usr/bin/env php
<?php

/**
 * Exemple de client API PHP pour consommer votre API
 *
 * Usage:
 *   php api-client.php health
 *   php api-client.php profile YOUR_TOKEN
 *   php api-client.php keys YOUR_TOKEN
 */

class ApiClient
{
    private string $baseUrl;
    private string $token;

    public function __construct(string $baseUrl, string $token = '')
    {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->token = $token;
    }

    /**
     * Effectuer une requête API
     */
    private function request(string $method, string $endpoint, ?array $data = null): array
    {
        $url = $this->baseUrl . '/api' . $endpoint;

        $options = [
            'http' => [
                'method' => $method,
                'header' => [
                    'Content-Type: application/json',
                ],
                'timeout' => 10,
            ],
        ];

        if ($this->token) {
            $options['http']['header'][] = "Authorization: Bearer {$this->token}";
        }

        if ($data && in_array($method, ['POST', 'PATCH', 'PUT'])) {
            $options['http']['content'] = json_encode($data);
        }

        $context = stream_context_create($options);
        $response = @file_get_contents($url, false, $context);

        if ($response === false) {
            return [
                'error' => 'Erreur de connexion',
                'url' => $url
            ];
        }

        return json_decode($response, true) ?? ['error' => 'Réponse invalide'];
    }

    // Endpoints

    public function health(): array
    {
        return $this->request('GET', '/health');
    }

    public function profile(): array
    {
        return $this->request('GET', '/profile');
    }

    public function listKeys(): array
    {
        return $this->request('GET', '/api-keys');
    }

    public function createKey(string $name, ?string $expiresAt = null): array
    {
        $data = ['name' => $name];
        if ($expiresAt) {
            $data['expiresAt'] = $expiresAt;
        }
        return $this->request('POST', '/api-keys', $data);
    }

    public function deleteKey(int $id): array
    {
        return $this->request('DELETE', "/api-keys/{$id}");
    }

    public function deactivateKey(int $id): array
    {
        return $this->request('PATCH', "/api-keys/{$id}/deactivate");
    }
}

// --- Utilisation de ligne de commande ---

if (php_sapi_name() !== 'cli') {
    die('Ce script doit être exécuté en ligne de commande');
}

$baseUrl = 'http://localhost:8000';
$command = $argv[1] ?? 'health';
$token = $argv[2] ?? '';

$client = new ApiClient($baseUrl, $token);

match($command) {
    'health' => output_result('Health Check', $client->health()),
    'profile' => require_token($token, fn() => output_result('Profil utilisateur', $client->profile())),
    'keys' => require_token($token, fn() => output_result('Clés API', $client->listKeys())),
    'create-key' => require_token($token, function() use ($client) {
        $name = $argv[3] ?? 'Nouvelle clé';
        $expires = $argv[4] ?? null;
        output_result('Création de clé', $client->createKey($name, $expires));
    }),
    'delete-key' => require_token($token, function() use ($client) {
        if (empty($argv[3])) {
            echo "Usage: php api-client.php delete-key TOKEN KEY_ID\n";
            return;
        }
        output_result('Suppression de clé', $client->deleteKey((int)$argv[3]));
    }),
    'deactivate-key' => require_token($token, function() use ($client) {
        if (empty($argv[3])) {
            echo "Usage: php api-client.php deactivate-key TOKEN KEY_ID\n";
            return;
        }
        output_result('Désactivation de clé', $client->deactivateKey((int)$argv[3]));
    }),
    default => show_help(),
};

function require_token(string $token, callable $fn)
{
    if (!$token) {
        echo "Erreur: Ce commande nécessite un token\n";
        echo "Usage: php api-client.php COMMAND TOKEN [OPTIONS]\n";
        return;
    }
    $fn();
}

function output_result(string $title, array $result)
{
    echo "\n$title\n";
    echo str_repeat('=', strlen($title)) . "\n\n";
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n\n";
}

function show_help()
{
    echo <<<'EOT'

📡 Client API pour votre application

Commandes disponibles:

  health                          - Vérifier l'état de l'API (pas de token requis)
  profile TOKEN                   - Afficher le profil utilisateur
  keys TOKEN                      - Lister les clés API
  create-key TOKEN [NAME] [EXP]   - Créer une nouvelle clé API
  delete-key TOKEN KEY_ID         - Supprimer une clé API
  deactivate-key TOKEN KEY_ID     - Désactiver une clé API

Exemples:

  # Vérifier l'état
  php api-client.php health

  # Afficher le profil
  php api-client.php profile abc123...xyz

  # Lister les clés
  php api-client.php keys abc123...xyz

  # Créer une clé avec expiration
  php api-client.php create-key abc123...xyz "Mon App" "2026-12-31"

  # Supprimer une clé
  php api-client.php delete-key abc123...xyz 1

EOT;
}

