<?php
/**
 * Scheduler table names.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\Database;

// phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception messages are escaped at UI boundaries.

use ScheduledChanges\Support\WpdbConnection;

/**
 * Resolves scheduler-owned tables for the current WordPress site.
 */
final class TableNames {
	private ?\wpdb $database;

	/**
	 * Creates a table-name resolver.
	 *
	 * @param \wpdb|null $database Optional WordPress database connection.
	 */
	public function __construct( ?\wpdb $database = null ) {
		$this->database = $database;
	}

	/**
	 * Returns all scheduler table names keyed by domain name.
	 *
	 * @return array<string, string>
	 */
	public function all(): array {
		$database = null === $this->database ? WpdbConnection::current() : $this->database;
		$prefix   = $database->prefix . 'scheduled_changes_';

		return array(
			'launches'           => $prefix . 'launches',
			'launch_versions'    => $prefix . 'launch_versions',
			'launch_targets'     => $prefix . 'launch_targets',
			'operations'         => $prefix . 'operations',
			'recording_sessions' => $prefix . 'recording_sessions',
			'runs'               => $prefix . 'runs',
			'run_operations'     => $prefix . 'run_operations',
				'snapshots'          => $prefix . 'snapshots',
				'audit_events'       => $prefix . 'audit_events',
				'notifications'      => $prefix . 'notifications',
				'locks'              => $prefix . 'locks',
			);
	}

	/**
	 * Resolves one scheduler table.
	 *
	 * @param string $name Domain table name.
	 */
	public function get( string $name ): string {
		$tables = $this->all();

		if ( ! isset( $tables[ $name ] ) ) {
			throw new \InvalidArgumentException( 'Unknown JJ\'s Post Scheduler table: ' . $name );
		}

		return $tables[ $name ];
	}
}
