<?php
namespace Bot;

use PDO;
use PDOException;

/**
 * Simple PDO wrapper for MySQL connections.
 *
 * This class centralises the creation of a PDO instance using settings
 * provided via the Config class. It ensures a single connection is reused
 * throughout the application. Should the database be unreachable, a
 * RuntimeException is thrown with a descriptive message.
 */
class Database
{
    /**
     * Internal PDO instance cache.
     *
     * @var PDO|null
     */
    private static ?PDO $pdo = null;

    /**
     * Obtain a PDO connection for the configured database.
     *
     * @throws \RuntimeException When connection fails.
     *
     * @return PDO
     */
    public static function connection(): PDO
    {
        if (self::$pdo === null) {
            $config = Config::get()->getValue('db');
            $dsn = sprintf(
                'mysql:host=%s;dbname=%s;port=%s;charset=utf8mb4',
                $config['host'],
                $config['database'],
                $config['port']
            );
            try {
                self::$pdo = new PDO($dsn, $config['user'], $config['password'], [
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                ]);
            } catch (PDOException $e) {
                throw new \RuntimeException('Database connection failed: ' . $e->getMessage());
            }
        }
        return self::$pdo;
    }
}