<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;

class OtpService
{
    private const TTL_MINUTES = 10;

    public function generate(string $key): string
    {
        $code = (string) random_int(100000, 999999);

        Cache::put($this->cacheKey($key), $code, now()->addMinutes(self::TTL_MINUTES));

        return $code;
    }

    public function verify(string $key, string $code): bool
    {
        $cached = Cache::get($this->cacheKey($key));

        if ($cached === null || $cached !== $code) {
            return false;
        }

        Cache::forget($this->cacheKey($key));

        return true;
    }

    private function cacheKey(string $key): string
    {
        return "otp:{$key}";
    }
}