<?php

namespace App\Services;

use Illuminate\Support\Str;
use Illuminate\Support\Facades\Cache;

class DynamicQrService
{
    public function issueShortToken(int $sessionId, int $ttlSeconds = 15): array
    {
        $nonce = strtoupper(Str::random(32)); // contoh: "A1B2C3D4"
        $payload = [
            'session_id' => $sessionId,
            'nonce'      => $nonce,
            'exp'        => now()->addSeconds($ttlSeconds)->timestamp,
            'iat'        => now()->timestamp,
        ];

        // Simpan payload di cache
        Cache::put("qr_payload:$nonce", $payload, $ttlSeconds);

        return [
            'token'   => $nonce,
            'payload' => $payload
        ];
    }

    public function verifyShortToken(string $nonce): array
    {
        $payload = Cache::get("qr_payload:$nonce");

        if (!$payload) {
            return ['ok' => false, 'reason' => 'invalid_or_expired'];
        }

        if (now()->timestamp > ($payload['exp'] ?? 0)) {
            return ['ok' => false, 'reason' => 'expired', 'payload' => $payload];
        }

        return ['ok' => true, 'payload' => $payload];
    }
}
