<?php
/**
 * File Path: includes/migrations/class-mbs-migration-4-15.php
 *
 * Migration 4.15 — mbs_book_meta: add idx_isbn13 index
 *
 * Phase E index audit (Sprint 161) found that MBS_Book_Meta_DAO::find_by_isbn()
 * issues a WHERE isbn13 = ? query with no covering index on the column, causing
 * a full table scan on every ISBN lookup.
 *
 * This migration adds KEY idx_isbn13 (isbn13) to mbs_book_meta.
 * Idempotent: SHOW INDEX guard skips the ALTER when the index already exists.
 * No backfill required — ALTER TABLE only changes the index structure.
 *
 * @package MyBookShowroom
 * @since   2.5.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Migration 4.15: add idx_isbn13 index to mbs_book_meta.
 */
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- DAO/migration: table names via $wpdb->prefix are trusted server-controlled values, not user input
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter -- same reason: $wpdb->prefix table names are safe; $where_sql is built from sanitized server-controlled inputs
class MBS_Migration_4_15 implements MBS_Migration { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * @return string Migration version string.
	 */
	public function version(): string {
		return '4.15';
	}

	/**
	 * Run the migration.
	 *
	 * Idempotent: checks SHOW INDEX before issuing ALTER TABLE.
	 * Safe to replay — second run is a no-op.
	 *
	 * @return void
	 */
	public function up(): void {
		global $wpdb;

		$table = $wpdb->prefix . 'mbs_book_meta';

		// Guard: skip if index already exists (e.g. replay or manual add).
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$exists = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- DAO layer -- direct DB access is intentional per MBS architecture
			$wpdb->prepare(
				"SELECT COUNT(*) FROM information_schema.STATISTICS
				 WHERE table_schema = DATABASE()
				   AND table_name   = %s
				   AND index_name   = 'idx_isbn13'",
				$table
			)
		);

		if ( (int) $exists > 0 ) {
			return;
		}

		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$wpdb->query( "ALTER TABLE {$table} ADD KEY idx_isbn13 (isbn13)" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- DAO layer -- direct DB access is intentional per MBS architecture
	}
}
