<?php
/**
 * Per-request memo of `wp_trx_ad_vehicle_specs` rows keyed by post ID.
 *
 * The list table renders 5+ columns per row, all of which read the same
 * specs row. Without memoization each post would issue 5+ identical
 * SELECT queries. Extracted from the original `AdminListTable::getSpecsRow`
 * static-cache pattern so collaborators can share the same memo without
 * leaking state across requests (one instance lives for one request).
 *
 * @package ThemeREX\AutoDealer\Admin\ListTable
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin\ListTable;

defined( 'ABSPATH' ) || exit;

final class SpecsRowCache {

	/**
	 * @var array<int, object|null>
	 */
	private array $cache = array();

	/**
	 * Fetch the specs row for a post, hitting the DB at most once per post per request.
	 *
	 * @param int $postId Post ID.
	 * @return object|null Row from $wpdb->get_row() or null if absent.
	 */
	public function get( int $postId ): ?object {
		if ( array_key_exists( $postId, $this->cache ) ) {
			return $this->cache[ $postId ];
		}

		global $wpdb;
		$table = $wpdb->prefix . 'trx_ad_vehicle_specs';

		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM `{$table}` WHERE post_id = %d", $postId ) );

		$this->cache[ $postId ] = $row ?: null;

		return $this->cache[ $postId ];
	}
}
