<?php
/**
 * File Path: includes/migrations/class-mbs-migration-4-1.php
 *
 * MBS_Migration_4_1 -- Schema 4.1 -- DISPLAY-2
 *
 * Adds `sales_rank INT UNSIGNED NULL` to mbs_pa_api_cache so the
 * Bestseller Badge feature can key on Amazon sales rank per ASIN.
 * Guard: idempotent -- checks INFORMATION_SCHEMA before ALTER.
 *
 * @package MyBookShowroom
 * @since   4.1.0
 */

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

/**
 * Class MBS_Migration_4_1
 *
 * @implements MBS_Migration
 */
// 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_1 implements MBS_Migration { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	public function version(): string {
		return '4.1';
	}

	public function up(): void {
		global $wpdb;
		$table = $wpdb->prefix . 'mbs_pa_api_cache';

		$exists = (int) $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.COLUMNS
				  WHERE TABLE_SCHEMA = DATABASE()
				    AND TABLE_NAME   = %s
				    AND COLUMN_NAME  = 'sales_rank'",
				$table
			)
		);

		if ( ! $exists ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- table name from $wpdb->prefix; DDL is static.
			$wpdb->query( "ALTER TABLE {$table} ADD COLUMN sales_rank INT UNSIGNED NULL DEFAULT NULL" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- DAO layer -- direct DB access is intentional per MBS architecture
		}
	}
}
