<?php

declare(strict_types=1);

namespace ApiModel\Infrastructure\Persistence\Repositories;

use ApiModel\Domain\Repository\PasswordResetRepositoryInterface;
use PDO;

final class PdoPasswordResetRepository implements PasswordResetRepositoryInterface
{
    public function __construct(private readonly PDO $pdo) {}

    public function deleteAllForEmail(string $email): void
    {
        $this->pdo->prepare('DELETE FROM auth.password_reset_codes WHERE email = ?')->execute([$email]);
    }

    public function insert(string $email, string $codeHash, string $expiresAt): void
    {
        $this->pdo->prepare(
            'INSERT INTO auth.password_reset_codes (email, code_hash, expires_at) VALUES (?,?,?)',
        )->execute([$email, $codeHash, $expiresAt]);
    }

    public function findLatestValid(string $email, string $codeHash): ?array
    {
        $st = $this->pdo->prepare(
            'SELECT * FROM auth.password_reset_codes WHERE email = ? AND code_hash = ? AND consumed_at IS NULL ORDER BY id DESC LIMIT 1',
        );
        $st->execute([$email, $codeHash]);
        $row = $st->fetch();

        return $row !== false ? $row : null;
    }

    public function markConsumedById(string $id): void
    {
        $this->pdo->prepare('UPDATE auth.password_reset_codes SET consumed_at = CURRENT_TIMESTAMP WHERE id = ?')->execute([$id]);
    }
}
