<?php

declare(strict_types=1);

namespace App\Models;

class PasswordReset extends BaseModel
{
    protected string $table = 'password_resets';
    protected string $primaryKey = 'id';

    public function createToken(int $userId, string $token, int $expiresIn = 3600): int
    {
        $this->execute(
            "INSERT INTO {$this->table} (user_id, token, expires_at, used)
             VALUES (:user_id, :token, DATE_ADD(NOW(), INTERVAL :seconds SECOND), 0)",
            [
                'user_id' => $userId,
                'token' => $token,
                'seconds' => $expiresIn,
            ]
        );

        return (int) $this->db->lastInsertId();
    }

    public function findValidToken(string $token): ?array
    {
        return $this->queryOne(
            "SELECT * FROM {$this->table} WHERE token = :token AND used = 0 AND expires_at > NOW() LIMIT 1",
            ['token' => $token]
        );
    }

    public function markAsUsed(int $id): bool
    {
        return $this->update($id, ['used' => 1]);
    }

    public function invalidateExistingTokens(int $userId): void
    {
        $this->execute(
            "UPDATE {$this->table} SET used = 1 WHERE user_id = :user_id AND used = 0",
            ['user_id' => $userId]
        );
    }
}
