<?php

namespace App\Services\Extension;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class ExtensionVerificationService
{
    /**
     * @param  array<string>  $expectedExtensionIds
     */
    public function verifyToken(string $token, array $expectedExtensionIds): bool
    {
        if ($token === '') {
            return false;
        }

        $config = config('dewemoji.extension_verification', []);
        if (! (bool) ($config['enabled'] ?? true)) {
            return true;
        }

        $projectId = (string) ($config['project_id'] ?? '');
        $serverKey = (string) ($config['server_key'] ?? '');
        if ($projectId === '' || $serverKey === '') {
            return false;
        }

        $cacheKey = 'dw_ext_verify_'.sha1($token);
        $ttl = max((int) ($config['cache_ttl'] ?? 3600), 60);

        return Cache::remember($cacheKey, $ttl, function () use ($token, $serverKey, $expectedExtensionIds): bool {
            $url = 'https://iid.googleapis.com/iid/info/'.$token.'?details=true';
            $response = Http::withHeaders([
                'Authorization' => 'key='.$serverKey,
            ])->get($url);

            if (! $response->ok()) {
                return false;
            }

            $data = $response->json();
            if (! is_array($data)) {
                return false;
            }

            $application = (string) ($data['application'] ?? '');
            if ($application === '') {
                return false;
            }

            if (count($expectedExtensionIds) === 0) {
                return true;
            }

            return in_array($application, $expectedExtensionIds, true);
        });
    }
}
