<?php
declare(strict_types=1);

/** User 2FA factors (TOTP alpha). */
final class AuthFactors {
    private function __construct() {
    }

    public static function ensureSchema(): void {
        AuthEmailSchema::ensure(Database::pdo());
    }

    public static function hasTotp(int $userId): bool {
        if ($userId <= 0) {
            return false;
        }
        self::ensureSchema();
        $st = Database::pdo()->prepare(
            "SELECT id FROM auth_factors WHERE user_id = ? AND type = 'totp' LIMIT 1"
        );
        $st->execute([$userId]);
        return (bool) $st->fetchColumn();
    }

    public static function getTotpSecret(int $userId): ?string {
        if ($userId <= 0) {
            return null;
        }
        self::ensureSchema();
        $st = Database::pdo()->prepare(
            "SELECT secret_encrypted FROM auth_factors WHERE user_id = ? AND type = 'totp' LIMIT 1"
        );
        $st->execute([$userId]);
        $enc = $st->fetchColumn();
        if (!is_string($enc) || $enc === '') {
            return null;
        }
        $plain = AuthCrypto::decrypt($enc);
        return $plain !== '' ? $plain : null;
    }

    public static function enrollTotp(int $userId, string $secret): void {
        self::ensureSchema();
        $enc = AuthCrypto::encrypt($secret);
        $pdo = Database::pdo();
        $pdo->prepare("DELETE FROM auth_factors WHERE user_id = ? AND type = 'totp'")->execute([$userId]);
        $pdo->prepare(
            'INSERT INTO auth_factors (user_id, type, secret_encrypted, label, created_at) VALUES (?, ?, ?, ?, ?)'
        )->execute([$userId, 'totp', $enc, 'Authenticator', date('Y-m-d H:i:s')]);
    }

    public static function removeTotp(int $userId): void {
        self::ensureSchema();
        Database::pdo()->prepare("DELETE FROM auth_factors WHERE user_id = ? AND type = 'totp'")->execute([$userId]);
    }
}
