<?php

namespace Velis\Notification\Mobile;

use Google\Auth\CredentialsLoader;
use Google\Auth\Middleware\AuthTokenMiddleware;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\HandlerStack;
use Velis\Http\Client;
use Velis\Http\ClientInterface;

/**
 * @author Jan Małysiak <jan.malysiak@velistech.com>
 */
class FcmClientFactory
{
    /**
     * @param string $configPath
     */
    public function __construct(private string $configPath)
    {
    }

    /**
     * @return ClientInterface
     */
    public function create(): ClientInterface
    {
        $stack = $this->createHandler();

        $guzzleClient = new GuzzleClient([
            'handler' => $stack,
            'auth' => 'google_auth',
        ]);

        return new Client($guzzleClient);
    }

    /**
     * @return HandlerStack
     */
    private function createHandler(): HandlerStack
    {
        $scopes = ['https://www.googleapis.com/auth/firebase.messaging'];
        $jsonKey = json_decode(file_get_contents(ROOT_PATH . $this->configPath), true);

        $credentials = CredentialsLoader::makeCredentials($scopes, $jsonKey);
        $middleware = new AuthTokenMiddleware($credentials);

        $stack = HandlerStack::create();
        $stack->push($middleware);

        return $stack;
    }
}
