<?php

namespace App\Services;

use Exception;
use Illuminate\Support\Facades\Http;
use stdClass;

class GoogleIdentityTokenService
{
    /**
     * Verify a Google ID token and return its claims.
     *
     * @throws Exception
     */
    public function verify(string $identityToken): stdClass
    {
        $response = Http::acceptJson()
            ->timeout(10)
            ->get(config('desxpert.google_verify') . $identityToken);

        if (!$response->successful()) {
            throw new Exception('Invalid Google token.');
        }

        $claims = $response->object();

        if (!$claims instanceof stdClass || empty($claims->email) || empty($claims->sub)) {
            throw new Exception('Invalid Google token.');
        }

        if (isset($claims->email_verified) && !filter_var($claims->email_verified, FILTER_VALIDATE_BOOLEAN)) {
            throw new Exception('Your Google email address is not verified.');
        }

        $allowedClientIds = config('desxpert.google_client_ids', []);

        if ($allowedClientIds !== [] && !in_array($claims->aud ?? null, $allowedClientIds, true)) {
            throw new Exception('This Google token was issued for another application.');
        }

        return $claims;
    }
}
