<?php

/**
 * This program is copyrighted by Franz Geffke (Softmax Co., Ltd.)
 */

namespace ones\oidc;

use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

/**
 * Request device access token
 * 
 * @param array $provider_metadata
 * @param string $device_client_id
 * @param string $device_jwt
 * 
 * @return array{
 *    access_token: string,
 *    expires_in: int,
 *    token_type: string
 * }
 */
function request_device_access_token(
    array $provider_metadata,
    string $device_client_id,
    string $device_jwt
) {
    $client = new Client();
    $url = $provider_metadata['token_endpoint'];

    $body = [
        'grant_type' => 'client_credentials',
        'client_id' => $device_client_id,
        'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
        'client_assertion' => $device_jwt,
    ];

    try {
        $response = $client->post($url, [
            'form_params' => $body,
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
            'timeout' => 3,
        ]);

        return json_decode($response->getBody(), true);
    } catch (RequestException $e) {
        // Handle error
        if ($e->hasResponse()) {
            $errorResponse = $e->getResponse()->getBody()->getContents();
            throw new Exception("Request failed: " . $errorResponse);
        } else {
            throw new Exception("Request failed: " . $e->getMessage());
        }
    }
}

?>