<?php

function db_config(): array
{
    static $config = null;

    if ($config === null) {
        $config = require __DIR__ . '/../config/database.php';
    }

    return $config;
}

function db_connect(string $dbname): PDO
{
    static $connections = [];

    if (!isset($connections[$dbname])) {
        $config = db_config();

        $dsn = sprintf(
            'mysql:host=%s;port=%d;dbname=%s;charset=%s',
            $config['host'],
            $config['port'],
            $dbname,
            $config['charset']
        );

        $connections[$dbname] = new PDO(
            $dsn,
            $config['user'],
            $config['password'],
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]
        );
    }

    return $connections[$dbname];
}

function platform_db(): PDO
{
    $config = db_config();
    return db_connect($config['platform_db']);
}

function telemetry_db(): PDO
{
    $config = db_config();
    return db_connect($config['telemetry_db']);
}

function telemetry_db_by_name(string $dbname): PDO
{
    return db_connect($dbname);
}
