<?php

namespace App\Domain\Services;

use App\Domain\Repositories\UserRepositoryInterface;
use App\Drivers\CacheDriver;
use App\Infrastructure\Mail\Mailer;
use App\Support\Str;

class EmailVerificationService
{
    public function __construct(
        private UserRepositoryInterface $users,
        private CacheDriver $cache,
        private Mailer $mailer
    ) {
    }

    public function issue(string $email): string
    {
        $token = Str::random(48);
        $user = $this->users->findByEmail($email);

        if ($user) {
            $this->cache->put('email-verify:' . hash('sha256', $token), $user->id, 86400);
            $this->mailer->send($email, 'Email verification token', 'Verification token: ' . $token);
        }

        return $token;
    }

    public function verify(string $token): bool
    {
        $key = 'email-verify:' . hash('sha256', $token);
        $ok = $this->cache->has($key);
        if ($ok) {
            $this->cache->forget($key);
        }

        return $ok;
    }
}
