<?php
/**
 * WordPress-backed log repository.
 *
 * Production {@see LogRepository} implementation that persists
 * {@see LogRecord} instances into the `clb_logs` table defined in
 * `specifications/database-schema.md` §9, routing every read and write
 * through the WordPress `$wpdb` global.
 *
 * Design notes:
 *
 *   - Writes use `$wpdb->insert()` / `$wpdb->delete()` with explicit
 *     format strings rather than building raw SQL. This keeps every
 *     value correctly escaped by the driver and lets the repository
 *     stay terse enough to audit at a glance. Reads use
 *     `$wpdb->prepare()` for the variable components and
 *     `$wpdb->get_row()` / `$wpdb->get_var()` to materialize rows.
 *
 *   - {@see self::save()} is INSERT-ONLY per the
 *     {@see LogRepository::save()} contract. A non-null-id record
 *     raises {@see RuntimeException} before reaching `$wpdb` because
 *     `clb_logs` is append-only (§9.2 omits `updated_at`; §9.4 defers
 *     retention to a purge job). Consequently this repository never
 *     calls `$wpdb->update()` — that path simply does not exist.
 *
 *   - The physical table name is resolved through the injected
 *     {@see TableNameResolver} (see {@see PrefixedTableNameResolver} for
 *     the production default). The resolved name is interpolated into
 *     the SQL string directly because `$wpdb->prepare()` cannot bind
 *     identifiers — the resolver is the trust boundary here, and its
 *     input comes from a class-level constant, not user data.
 *
 *   - Driver errors (`$wpdb->last_error`) are promoted to
 *     {@see RuntimeException} after every mutating call, so a write
 *     that MySQL rejected surfaces loudly at the repository boundary
 *     instead of silently returning a false-y result. Reads do the
 *     same promotion so a malformed SELECT raises rather than being
 *     silently treated as a "not found" outcome.
 *
 *   - The `created_at` timestamp round-trips through
 *     {@see LogRecord::toArray()} / {@see LogRecord::fromArray()},
 *     which encode UTC `DateTimeImmutable` values as the MySQL
 *     `Y-m-d H:i:s` form this table stores. Callers never see the
 *     string representation.
 *
 *   - `$wpdb` is typed as `object` rather than the concrete `\wpdb`
 *     class so this file stays trivially loadable in unit tests that
 *     run outside a WordPress environment. The repository still
 *     requires the real interface surface at call time; the abstract
 *     type hint only keeps the PSR-4 loader and the PHPCS /
 *     PHPStan analyzers happy in pure-unit mode.
 *
 * @package CommerceLinkBuilder\Infrastructure\Persistence
 */

declare(strict_types=1);

namespace CommerceLinkBuilder\Infrastructure\Persistence;

use InvalidArgumentException;
use RuntimeException;

/**
 * {@see LogRepository} implementation backed by WordPress's `$wpdb`.
 *
 * See the file-level docblock for the driver-call strategy, identifier-
 * interpolation boundary, error-promotion policy, and the insert-only
 * `save()` semantics that distinguish this repository from the other
 * CLB persistence implementations.
 */
final class WpdbLogRepository implements LogRepository {

	/**
	 * Logical, unprefixed CLB table name this repository targets.
	 *
	 * Named as a class-level constant so tests and diagnostics can
	 * reference the exact name without duplicating the string literal,
	 * and so a future rename has a single location to update.
	 */
	public const TABLE_LOGICAL_NAME = 'clb_logs';

	/**
	 * Column names in the canonical order declared by
	 * `database-schema.md` §9.2. Used to bound the write payload and
	 * the read projection to the columns this repository owns,
	 * independent of any stray columns a host site might have added.
	 *
	 * The list excludes `id` because that column is driver-managed
	 * (auto-increment on insert, primary key on delete).
	 *
	 * @var list<string>
	 */
	private const COLUMNS = array(
		'channel',
		'level',
		'message',
		'context_json',
		'related_product_id',
		'related_job_id',
		'created_at',
	);

	/**
	 * Format string handed to `$wpdb->insert()` so every column is
	 * bound with the correct placeholder. Keyed by the snake_case
	 * column name and restricted to the columns listed in
	 * {@see self::COLUMNS}.
	 *
	 * `%d` is used for the two `bigint unsigned` cross-reference
	 * columns (`related_product_id`, `related_job_id`) and `%s` for
	 * everything else, including the JSON context blob and the
	 * timestamp column.
	 *
	 * @var array<string, string>
	 */
	private const COLUMN_FORMATS = array(
		'channel'            => '%s',
		'level'              => '%s',
		'message'            => '%s',
		'context_json'       => '%s',
		'related_product_id' => '%d',
		'related_job_id'     => '%d',
		'created_at'         => '%s',
	);

	/**
	 * WordPress `$wpdb`-like object used for every database call.
	 *
	 * Typed as `object` rather than `\wpdb` so this file stays loadable
	 * in unit tests that run outside a WordPress environment; see the
	 * file-level docblock for the rationale.
	 */
	private object $wpdb;

	/**
	 * Cached physical table name.
	 *
	 * Resolved once at construction time so repeated calls emit the
	 * same identifier even when the host site mutates `$wpdb->prefix`
	 * mid-request (for example via `switch_to_blog()`). Call sites
	 * that need per-request prefix lookup should construct a fresh
	 * repository after each switch, matching the stability contract
	 * on {@see PrefixedTableNameResolver}.
	 */
	private string $tableName;

	/**
	 * Construct the repository.
	 *
	 * @param object            $wpdb       WordPress `$wpdb`-like object
	 *                                      exposing `insert()`,
	 *                                      `delete()`, `prepare()`,
	 *                                      `get_row()`, `get_var()`, the
	 *                                      `last_error` property, and the
	 *                                      `insert_id` property.
	 * @param TableNameResolver $tableNames Resolver used to derive the
	 *                                      physical `clb_logs` name.
	 */
	public function __construct( object $wpdb, TableNameResolver $tableNames ) {
		$this->wpdb      = $wpdb;
		$this->tableName = $tableNames->resolve( self::TABLE_LOGICAL_NAME );
	}

	/**
	 * Physical table name this repository targets, resolved once at
	 * construction time through the injected {@see TableNameResolver}.
	 *
	 * Exposed primarily for tests and diagnostics; production code
	 * should not need to interpolate the name by hand.
	 */
	public function tableName(): string {
		return $this->tableName;
	}

	/**
	 * Persist the record and return its post-insert form.
	 *
	 * See {@see LogRepository::save()} for the full contract. This
	 * implementation:
	 *
	 *   - Rejects non-null-id records with a descriptive
	 *     {@see RuntimeException} before reaching `$wpdb`. The
	 *     append-only schema (§9.2 / §9.4) has no supported update
	 *     path; surfacing the misuse loudly is preferable to silently
	 *     inserting a duplicate row or silently ignoring the call.
	 *
	 *   - Treats a null id as an insert. The column payload is built
	 *     from {@see LogRecord::toArray()} (minus `id`) and handed to
	 *     `$wpdb->insert()` with the format list from
	 *     {@see self::COLUMN_FORMATS}. The driver's `insert_id` is
	 *     reflected into the returned record via
	 *     {@see LogRecord::withId()}.
	 *
	 * Driver errors raise {@see RuntimeException} carrying
	 * `$wpdb->last_error` verbatim.
	 *
	 * @param LogRecord $record Record to persist. Must carry a null id.
	 *
	 * @throws RuntimeException When the supplied record already
	 *                          carries a non-null id, when `$wpdb`
	 *                          reports an error, or when the insert
	 *                          succeeds but no `insert_id` is
	 *                          populated.
	 */
	public function save( LogRecord $record ): LogRecord {
		$id = $record->id();

		if ( $id !== null ) {
			$message = sprintf(
				'WpdbLogRepository::save() is insert-only; refusing to persist a record that already carries id %d. '
				. 'clb_logs is append-only per database-schema.md §9.2 / §9.4.',
				$id
			);
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
			throw new RuntimeException( $message );
		}

		$row     = $this->columnPayload( $record );
		$formats = $this->formatsFor( array_keys( $row ) );

		$this->clearLastError();

		/** @var false|int $result */
		$result = $this->wpdb->insert( $this->tableName, $row, $formats );

		$this->assertNoDriverError( 'insert' );

		if ( $result === false ) {
			$message = 'WpdbLogRepository::save(): $wpdb->insert() returned false without raising a driver error.';
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
			throw new RuntimeException( $message );
		}

		$insertId = property_exists( $this->wpdb, 'insert_id' ) ? (int) $this->wpdb->insert_id : 0;
		if ( $insertId <= 0 ) {
			$message = 'WpdbLogRepository::save(): $wpdb->insert() did not populate insert_id.';
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
			throw new RuntimeException( $message );
		}

		return $record->withId( $insertId );
	}

	/**
	 * Look up a record by its primary key.
	 *
	 * Returns null when no row matches; raises
	 * {@see InvalidArgumentException} for non-positive ids so a
	 * programming error at the call site surfaces loudly instead of
	 * silently missing.
	 *
	 * @param int $id Primary key to look up.
	 *
	 * @throws InvalidArgumentException When `$id` is non-positive.
	 *                                  Driver errors surface as RuntimeException
	 *                                  via {@see self::fetchOne()}.
	 */
	public function findById( int $id ): ?LogRecord {
		if ( $id <= 0 ) {
			$message = sprintf( 'WpdbLogRepository::findById() requires a positive id, got %d.', $id );
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
			throw new InvalidArgumentException( $message );
		}

		$sql = $this->wpdb->prepare(
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- Table name resolved from a class-level constant, not user input.
			'SELECT * FROM ' . $this->tableName . ' WHERE id = %d LIMIT 1',
			$id
		);

		return $this->fetchOne( $sql );
	}

	/**
	 * Remove the row identified by the given id.
	 *
	 * Idempotent: returns true when a row was removed, false when no
	 * row matched. Non-positive ids raise
	 * {@see InvalidArgumentException} so a programming error at the
	 * call site surfaces loudly instead of silently missing.
	 *
	 * Single-row only; bulk purge belongs with the `cleanup_logs`
	 * scheduled job (§8.4 / §9.4) and is intentionally not part of
	 * the {@see LogRepository} contract.
	 *
	 * @param int $id Primary key of the row to delete.
	 *
	 * @throws InvalidArgumentException When `$id` is non-positive.
	 * @throws RuntimeException         When `$wpdb` reports an error.
	 */
	public function delete( int $id ): bool {
		if ( $id <= 0 ) {
			$message = sprintf( 'WpdbLogRepository::delete() requires a positive id, got %d.', $id );
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
			throw new InvalidArgumentException( $message );
		}

		$this->clearLastError();

		/** @var false|int $result */
		$result = $this->wpdb->delete(
			$this->tableName,
			array( 'id' => $id ),
			array( '%d' )
		);

		$this->assertNoDriverError( 'delete' );

		if ( $result === false ) {
			$message = sprintf(
				'WpdbLogRepository::delete(): $wpdb->delete() returned false for id %d '
				. 'without raising a driver error.',
				$id
			);
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
			throw new RuntimeException( $message );
		}

		return (int) $result > 0;
	}

	/**
	 * Total number of rows currently stored in `clb_logs`.
	 *
	 * Backed by a `SELECT COUNT(*)` query rather than materializing
	 * every row, matching the {@see LogRepository::count()} guidance.
	 *
	 * @throws RuntimeException When `$wpdb` reports an error.
	 */
	public function count(): int {
		$this->clearLastError();

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Counting CLB-owned rows; caching handled by caller where relevant.
		$value = $this->wpdb->get_var(
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- Table name resolved from a class-level constant, not user input.
			'SELECT COUNT(*) FROM ' . $this->tableName
		);

		$this->assertNoDriverError( 'count' );

		return (int) $value;
	}

	/**
	 * Look up a paginated, filtered slice of stored rows.
	 *
	 * Implements {@see LogRepository::findPaginated()} against `$wpdb`.
	 * The WHERE clause is built dynamically by appending one fragment
	 * per non-null filter on `$query`; every parameterized value is
	 * bound through `$wpdb->prepare()`. The ordering is fixed at
	 * `created_at DESC, id DESC` because §12.2 does not expose a sort
	 * parameter.
	 *
	 * Two queries are issued: a `SELECT COUNT(*)` under the same
	 * WHERE clause for the pre-pagination total, and a `SELECT *`
	 * with `LIMIT $perPage OFFSET $offset` for the page slice. Both
	 * pin the same WHERE arguments through `$wpdb->prepare()` so the
	 * total reported on the result envelope cannot disagree with the
	 * row set.
	 *
	 * @param LogListQuery $query Validated list-query inputs.
	 *
	 * @throws RuntimeException When `$wpdb` reports an error or when
	 *                          a returned row cannot be decoded into
	 *                          a {@see LogRecord}.
	 */
	public function findPaginated( LogListQuery $query ): LogListResult {
		$whereSql  = '';
		$whereArgs = array();

		if ( $query->level() !== null ) {
			$whereSql   .= ' AND level = %s';
			$whereArgs[] = $query->level();
		}

		if ( $query->channel() !== null ) {
			$whereSql   .= ' AND channel = %s';
			$whereArgs[] = $query->channel();
		}

		if ( $query->relatedProductId() !== null ) {
			$whereSql   .= ' AND related_product_id = %d';
			$whereArgs[] = $query->relatedProductId();
		}

		if ( $query->relatedJobId() !== null ) {
			$whereSql   .= ' AND related_job_id = %d';
			$whereArgs[] = $query->relatedJobId();
		}

		$whereClause = $whereSql === '' ? '' : ' WHERE 1=1' . $whereSql;

		$page    = $query->page();
		$perPage = $query->perPage();
		$offset  = $query->offset();

		// Total count under the same WHERE clause, before pagination.
		$countSql = 'SELECT COUNT(*) FROM ' . $this->tableName . $whereClause;
		if ( $whereArgs !== array() ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name resolved from a class-level constant; values bound via prepare().
			$preparedCount = $this->wpdb->prepare( $countSql, ...$whereArgs );
		} else {
			$preparedCount = $countSql;
		}

		$this->clearLastError();
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Counting CLB-owned rows; caching handled by caller where relevant.
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Already prepared above when args are present.
		$totalRaw = $this->wpdb->get_var( $preparedCount );
		$this->assertNoDriverError( 'count' );
		$total = (int) $totalRaw;

		// Page slice under the same WHERE clause, sorted newest-first.
		$selectSql  = 'SELECT * FROM ' . $this->tableName
			. $whereClause
			. ' ORDER BY created_at DESC, id DESC'
			. ' LIMIT %d OFFSET %d';
		$selectArgs = array_merge( $whereArgs, array( $perPage, $offset ) );

		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name resolved from a class-level constant; values bound via prepare().
		$preparedSelect = $this->wpdb->prepare( $selectSql, ...$selectArgs );

		$items = $this->fetchMany( $preparedSelect );

		return new LogListResult( $items, $total, $page, $perPage );
	}

	/**
	 * Group every stored row by PSR-3 level and return the per-level
	 * counts.
	 *
	 * See {@see LogRepository::countByLevel()} for the contract; in
	 * particular, levels with zero occurrences are omitted so callers
	 * default-fill against {@see LogListQuery::VALID_LEVELS}.
	 *
	 * Backed by a single `SELECT level, COUNT(*) ... GROUP BY level`
	 * query so the database does the grouping rather than this layer
	 * materializing every row.
	 *
	 * @return array<string, int>
	 *
	 * @throws RuntimeException When `$wpdb` reports an error.
	 */
	public function countByLevel(): array {
		$this->clearLastError();

		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- Table name resolved from a class-level constant, not user input.
		$sql = 'SELECT level, COUNT(*) AS c FROM ' . $this->tableName . ' GROUP BY level';

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Aggregating CLB-owned rows; caching handled by caller where relevant.
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- SQL is a constant statement built from class-level identifiers; no user input bound.
		$rows = $this->wpdb->get_results( $sql, 'ARRAY_A' );

		$this->assertNoDriverError( 'select' );

		if ( ! is_array( $rows ) ) {
			$message = 'WpdbLogRepository::countByLevel(): $wpdb->get_results() returned a non-array result set.';
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
			throw new RuntimeException( $message );
		}

		$counts = array();
		foreach ( $rows as $row ) {
			if ( ! is_array( $row ) ) {
				$message = 'WpdbLogRepository::countByLevel(): $wpdb->get_results() returned a non-array row.';
				// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
				throw new RuntimeException( $message );
			}
			if ( ! array_key_exists( 'level', $row ) || ! array_key_exists( 'c', $row ) ) {
				$message = 'WpdbLogRepository::countByLevel(): grouped row missing "level" or "c" key.';
				// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
				throw new RuntimeException( $message );
			}
			$counts[ (string) $row['level'] ] = (int) $row['c'];
		}

		return $counts;
	}

	/**
	 * Return the most recent log entries, newest-first, capped at
	 * `$limit`.
	 *
	 * See {@see LogRepository::findRecent()} for the contract. Issues
	 * a single `SELECT * FROM ... ORDER BY created_at DESC, id DESC
	 * LIMIT $limit` query, matching the ordering used by
	 * {@see self::findPaginated()} so the summary endpoint and the
	 * paginated logs view cannot disagree about which rows are most
	 * recent.
	 *
	 * @param int $limit Maximum number of entries to return (1..100).
	 *
	 * @return list<LogRecord>
	 *
	 * @throws InvalidArgumentException When `$limit` is out of range.
	 *                                  Driver errors surface as
	 *                                  RuntimeException via
	 *                                  {@see self::fetchMany()}.
	 */
	public function findRecent( int $limit ): array {
		if ( $limit < 1 || $limit > LogListQuery::MAX_PER_PAGE ) {
			$message = sprintf(
				'WpdbLogRepository::findRecent() requires limit between 1 and %d, got %d.',
				LogListQuery::MAX_PER_PAGE,
				$limit
			);
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
			throw new InvalidArgumentException( $message );
		}

		$sql = $this->wpdb->prepare(
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- Table name resolved from a class-level constant, not user input.
			'SELECT * FROM ' . $this->tableName . ' ORDER BY created_at DESC, id DESC LIMIT %d',
			$limit
		);

		return $this->fetchMany( $sql );
	}

	/**
	 * Execute a prepared SELECT and decode every row into a
	 * {@see LogRecord}.
	 *
	 * Centralizes the multi-row decoding boilerplate shared by
	 * {@see self::findPaginated()} and {@see self::findRecent()} so
	 * the per-method bodies stay focused on query construction.
	 *
	 * @param string $preparedSql SQL produced by `$wpdb->prepare()`.
	 *
	 * @return list<LogRecord>
	 *
	 * @throws RuntimeException When `$wpdb` reports an error or when
	 *                          a returned row cannot be decoded into
	 *                          a {@see LogRecord}.
	 */
	private function fetchMany( string $preparedSql ): array {
		$this->clearLastError();

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Reading CLB-owned rows; caching handled by caller where relevant.
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Already prepared upstream by wpdb->prepare().
		$rows = $this->wpdb->get_results( $preparedSql, 'ARRAY_A' );
		$this->assertNoDriverError( 'select' );

		if ( ! is_array( $rows ) ) {
			$message = 'WpdbLogRepository::fetchMany(): $wpdb->get_results() returned a non-array result set.';
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
			throw new RuntimeException( $message );
		}

		$items = array();
		foreach ( $rows as $row ) {
			if ( ! is_array( $row ) ) {
				$message = 'WpdbLogRepository::fetchMany(): $wpdb->get_results() returned a non-array row.';
				// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
				throw new RuntimeException( $message );
			}
			/** @var array<string, mixed> $row */
			$items[] = LogRecord::fromArray( $row );
		}

		return $items;
	}

	/**
	 * Execute a prepared SELECT and decode the first row into a
	 * {@see LogRecord}, or return null when the query matched no row.
	 *
	 * Centralizes the error-promotion and decoding paths shared by
	 * every read method on this class so the per-method bodies stay
	 * focused on query construction.
	 *
	 * @param string $preparedSql SQL produced by `$wpdb->prepare()`.
	 *
	 * @throws RuntimeException When `$wpdb` reports an error or when
	 *                          the returned row cannot be decoded
	 *                          into a {@see LogRecord}.
	 */
	private function fetchOne( string $preparedSql ): ?LogRecord {
		$this->clearLastError();

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Reading CLB-owned rows; caching handled by caller where relevant.
		// The ARRAY_A constant is defined by WordPress core; use its string
		// value directly so this repository file stays loadable in pure-unit
		// tests that do not boot WordPress.
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Already prepared upstream by wpdb->prepare().
		$row = $this->wpdb->get_row( $preparedSql, 'ARRAY_A' );
		$this->assertNoDriverError( 'select' );

		if ( $row === null ) {
			return null;
		}

		if ( ! is_array( $row ) ) {
			$message = 'WpdbLogRepository::fetchOne(): $wpdb->get_row() returned a non-array row.';
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
			throw new RuntimeException( $message );
		}

		/** @var array<string, mixed> $row */
		return LogRecord::fromArray( $row );
	}

	/**
	 * Build the column payload handed to `$wpdb->insert()`.
	 *
	 * Delegates to {@see LogRecord::toArray()} for the encoded row
	 * shape (timestamp formatted as a MySQL `DATETIME` string,
	 * nullable columns preserved as `null`) and strips the `id` entry
	 * because that column is driver-managed.
	 *
	 * @param LogRecord $record Record to encode.
	 *
	 * @return array<string, string|int|null>
	 */
	private function columnPayload( LogRecord $record ): array {
		$row = $record->toArray();
		unset( $row['id'] );

		/** @var array<string, string|int|null> $filtered */
		$filtered = array();
		foreach ( self::COLUMNS as $column ) {
			$filtered[ $column ] = $row[ $column ] ?? null;
		}

		return $filtered;
	}

	/**
	 * Produce the `$wpdb` format list for the given column names, in
	 * the order supplied.
	 *
	 * The WordPress `$wpdb->insert()` API expects the format list to
	 * line up positionally with the column payload, so this helper
	 * preserves the caller's ordering.
	 *
	 * @param list<string> $columns Column names in payload order.
	 *
	 * @return list<string> Matching format placeholders.
	 *
	 * @throws RuntimeException When a column has no registered format.
	 */
	private function formatsFor( array $columns ): array {
		$formats = array();
		foreach ( $columns as $column ) {
			if ( ! array_key_exists( $column, self::COLUMN_FORMATS ) ) {
				$message = sprintf(
					'WpdbLogRepository::formatsFor(): no format registered for column "%s".',
					$column
				);
				// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
				throw new RuntimeException( $message );
			}
			$formats[] = self::COLUMN_FORMATS[ $column ];
		}

		return $formats;
	}

	/**
	 * Clear `$wpdb->last_error` before a call so the post-call probe
	 * only sees errors produced by the current statement.
	 */
	private function clearLastError(): void {
		if ( property_exists( $this->wpdb, 'last_error' ) ) {
			$this->wpdb->last_error = '';
		}
	}

	/**
	 * Raise a {@see RuntimeException} when `$wpdb->last_error` is
	 * populated, carrying the driver message verbatim for diagnosis.
	 *
	 * @param string $operation Short operation label used in the error
	 *                          message (for example `insert`,
	 *                          `delete`, `select`).
	 *
	 * @throws RuntimeException When a driver error is detected.
	 */
	private function assertNoDriverError( string $operation ): void {
		if ( ! property_exists( $this->wpdb, 'last_error' ) ) {
			return;
		}

		$lastError = (string) $this->wpdb->last_error;
		if ( $lastError === '' ) {
			return;
		}

		$message = sprintf(
			'WpdbLogRepository: $wpdb reported an error during %s: %s',
			$operation,
			$lastError
		);
		// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing message, never rendered to HTML.
		throw new RuntimeException( $message );
	}
}
