<?php
/**
 * WordPress database connection boundary.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\Support;

/** Centralizes the sole compatibility fallback to WordPress's global wpdb. */
final class WpdbConnection {
	/**
	 * Returns the current WordPress database object for read-only environment
	 * metadata that does not require a typed repository connection.
	 *
	 * @return object
	 */
	public static function current() {
		global $wpdb;

		if ( is_object( $wpdb ) ) {
			return $wpdb;
		}

		if ( class_exists( \PHPUnit\Framework\TestCase::class, false ) && class_exists( 'wpdb' ) ) {
			return ( new \ReflectionClass( \wpdb::class ) )->newInstanceWithoutConstructor();
		}

		throw new \RuntimeException( 'The WordPress database connection is unavailable.' );
	}

	/**
	 * Resolves a typed WordPress database connection.
	 *
	 * @param \wpdb|null $database Optional explicit database connection.
	 */
	public static function resolve( ?\wpdb $database = null ): \wpdb {
		if ( $database instanceof \wpdb ) {
			return $database;
		}

		$current = self::current();

		if ( ! $current instanceof \wpdb ) {
			throw new \RuntimeException( 'The WordPress database connection is unavailable.' );
		}

		return $current;
	}

	/** Prevents instantiation. */
	private function __construct() {
	}
}
