<?php

namespace App\Service;

use App\Enum\Role;
use App\Enum\SecretName;
use App\Service\SecretManagerService;
use Symfony\Contracts\HttpClient\HttpClientInterface;


class KeycloakClientService
{
    private $httpClient;
    private string $oidc_auth_server_url;
    private string $oidc_client_id;
    private string $oidc_admin_username;
    private string $oidc_admin_password;
    private string $oidc_realm;

    public function __construct(
        HttpClientInterface $httpClient,
        string $oidc_auth_server_url,
        string $oidc_client_id,
        string $oidc_admin_username,
        string $oidc_admin_password,
        string $oidc_realm
    ) {
        $this->httpClient = $httpClient;
        $this->oidc_auth_server_url = $oidc_auth_server_url;
        $this->oidc_client_id = $oidc_client_id;
        $this->oidc_admin_username = $oidc_admin_username;
        $this->oidc_admin_password = $oidc_admin_password;
        $this->oidc_realm = $oidc_realm;
    }

    private function getAccessToken(): string
    {
        $tokenUrl = $this->oidc_auth_server_url . '/realms/master/protocol/openid-connect/token';

        $response = $this->httpClient->request('POST', $tokenUrl, [
            'body' => [
                'grant_type' => 'password',
                'client_id' => 'admin-cli',
                'username' => $this->oidc_admin_username,
                'password' => $this->oidc_admin_password,
            ],
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
        ]);
        $data = $response->toArray();
        $accessToken = $data['access_token'];

        return $accessToken;
    }

    public function logout(string $keyloakUserId): bool
    {

        $url = $this->oidc_auth_server_url . "/admin/realms/" . $this->oidc_realm . "/users/$keyloakUserId/logout";

        $this->httpClient->request('POST', $url, [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->getAccessToken(),
            ],
        ]);

        return true;
    }
}
