<?php

namespace App\Support\Security;

use App\Models\ApiNonce;
use Carbon\CarbonImmutable;

class NonceService
{
    public function ensureFreshAndStore(string $keyId, string $nonce, int $requestTs, int $ttlSeconds = 300): bool
    {
        $now = CarbonImmutable::now();
        $requestTime = CarbonImmutable::createFromTimestampUTC($requestTs);

        if ($requestTime->lt($now->subSeconds($ttlSeconds)) || $requestTime->gt($now->addSeconds(30))) {
            return false;
        }

        $exists = ApiNonce::query()->where('key_id', $keyId)->where('nonce', $nonce)->exists();
        if ($exists) {
            return false;
        }

        ApiNonce::query()->create([
            'key_id' => $keyId,
            'nonce' => $nonce,
            'request_ts' => $requestTime,
            'expires_at' => $now->addSeconds($ttlSeconds),
        ]);

        ApiNonce::query()->where('expires_at', '<', $now)->delete();

        return true;
    }
}
