<?php
/**
 * File Path: includes/migrations/class-mbs-migration-4-40.php
 *
 * Migration 4.40 -- Widen returnability column from VARCHAR(2) to VARCHAR(3)
 *
 * The returnability column was originally defined as VARCHAR(2), which fits
 * 'no' (2 chars) but silently rejects 'yes' (3 chars) via WordPress
 * $wpdb column-length validation before the INSERT is sent. This caused all
 * non-audiobook format rows to fail silently during tutorial import because
 * every print/ebook/boardbook/other row carries returnability = 'yes'.
 *
 * Guard: INFORMATION_SCHEMA.COLUMNS CHARACTER_MAXIMUM_LENGTH check prevents
 * double-application. The migration is fully idempotent.
 *
 * @package MyBookShowroom
 * @since   4.40.0
 */

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

/**
 * Migration 4.40: widen returnability VARCHAR(2) -> VARCHAR(3) in mbs_format_rows.
 */
// 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_40 implements MBS_Migration { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Returns the migration version string.
	 *
	 * @return string
	 */
	public function version(): string { return '4.40'; }

	/**
	 * Run the migration.
	 *
	 * Widens returnability to VARCHAR(3) so that the value 'yes' (3 chars)
	 * passes WordPress $wpdb column-length validation and can be inserted.
	 *
	 * @return void
	 */
	public function up(): void {
		global $wpdb;

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

		$current_length = (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 CHARACTER_MAXIMUM_LENGTH
				   FROM information_schema.COLUMNS
				  WHERE table_schema = DATABASE()
				    AND table_name   = %s
				    AND column_name  = 'returnability'",
				$table
			)
		);

		if ( $current_length < 3 ) {
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.SchemaChange
			$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- DAO layer -- direct DB access is intentional per MBS architecture
				"ALTER TABLE `{$table}`
				   MODIFY COLUMN returnability VARCHAR(3) NULL DEFAULT NULL"
			);
			// phpcs:enable WordPress.DB.DirectDatabaseQuery.SchemaChange
		}
	}
}
