<?php
namespace Misuzu\Auth;

use Index\XString;
use Index\Data\DbStatementCache;
use Index\Data\IDbConnection;
use Misuzu\Users\UserInfo;

class TwoFactorAuthSessions {
    private DbStatementCache $cache;

    public function __construct(IDbConnection $dbConn) {
        $this->cache = new DbStatementCache($dbConn);
    }

    private static function generateToken(): string {
        return XString::random(32);
    }

    public function createToken(UserInfo|string $userInfo): string {
        if($userInfo instanceof UserInfo)
            $userInfo = $userInfo->getId();

        $token = self::generateToken();

        $stmt = $this->cache->get('INSERT INTO msz_auth_tfa (user_id, tfa_token) VALUES (?, ?)');
        $stmt->addParameter(1, $userInfo);
        $stmt->addParameter(2, $token);
        $stmt->execute();

        return $token;
    }

    public function getTokenUserId(string $token): string {
        $stmt = $this->cache->get('SELECT user_id FROM msz_auth_tfa WHERE tfa_token = ? AND tfa_created > NOW() - INTERVAL 15 MINUTE');
        $stmt->addParameter(1, $token);
        $stmt->execute();
        $result = $stmt->getResult();

        return $result->next() ? $result->getString(0) : '';
    }

    public function deleteToken(string $token): void {
        $stmt = $this->cache->get('DELETE FROM msz_auth_tfa WHERE tfa_token = ?');
        $stmt->addParameter(1, $token);
        $stmt->execute();
    }
}
