<?php

namespace App\Domain\Services;

use App\Domain\Repositories\UserRepositoryInterface;
use App\Drivers\CacheDriver;
use App\Exceptions\AuthException;
use App\Infrastructure\Mail\Mailer;
use App\Infrastructure\Security\PasswordHasher;
use App\Support\Str;

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

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

        if ($user) {
            $this->cache->put('password-reset:' . hash('sha256', $token), $user->id, 3600);
            $this->mailer->send($email, 'Password reset token', 'Reset token: ' . $token);
        }

        return $token;
    }

    public function reset(string $token, string $password): void
    {
        $key = 'password-reset:' . hash('sha256', $token);
        $userId = $this->cache->get($key);
        if (!$userId) {
            throw new AuthException('Invalid or expired reset token', 400);
        }

        $this->users->updatePassword((int)$userId, $this->hasher->hash($password));
        $this->cache->forget($key);
    }
}
