<?php
declare(strict_types=1);

/** PDO to MariaDB `url_shortener` (separate from crashes DB). */
final class UrlShortenerDatabase {
    private static ?PDO $pdo = null;

    public static function enabled(): bool {
        return (bool) cfg('url_shortener.enabled', false);
    }

    public static function publicBase(): string {
        return rtrim((string) cfg('url_shortener.public_base', 'https://s.f0xx.org'), '/');
    }

    public static function pdo(): PDO {
        if (!self::enabled()) {
            throw new RuntimeException('url_shortener.enabled is false');
        }
        if (self::$pdo !== null) {
            return self::$pdo;
        }
        $m = cfg('url_shortener.db.mysql', []);
        if (!is_array($m) || ($m['database'] ?? '') === '') {
            throw new RuntimeException('url_shortener.db.mysql not configured');
        }
        $db = (string) $m['database'];
        $charset = (string) ($m['charset'] ?? 'utf8mb4');
        $socket = trim((string) ($m['socket'] ?? ''));
        if ($socket !== '') {
            $dsn = sprintf('mysql:unix_socket=%s;dbname=%s;charset=%s', $socket, $db, $charset);
        } else {
            $dsn = sprintf(
                'mysql:host=%s;port=%d;dbname=%s;charset=%s',
                $m['host'] ?? '127.0.0.1',
                (int) ($m['port'] ?? 3306),
                $db,
                $charset
            );
        }
        self::$pdo = new PDO($dsn, (string) ($m['username'] ?? ''), (string) ($m['password'] ?? ''), [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
        return self::$pdo;
    }

    public static function ping(): bool {
        if (!self::enabled()) {
            return false;
        }
        try {
            self::pdo()->query('SELECT 1');
            return true;
        } catch (Throwable) {
            return false;
        }
    }
}
