<?php
/**
 * File Path: includes/migrations/class-mbs-migration-4-25.php
 *
 * Migration 4.25 -- Sprint 180: Reader Links Icon Refactor
 *
 * Adds three columns to mbs_buy_links via dbDelta (no data loss):
 *   link_type          VARCHAR(20)  NOT NULL DEFAULT 'buy'
 *   link_label         VARCHAR(100) NULL DEFAULT NULL
 *   icon_attachment_id INT UNSIGNED NULL DEFAULT NULL
 *
 * Idempotency: dbDelta only adds columns absent from the live table.
 * Backfill: existing rows default to link_type = 'buy' via the
 *   NOT NULL DEFAULT constraint — no explicit UPDATE needed.
 *
 * @package MyBookShowroom
 * @since   1.4.0
 */

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

/**
 * Migration 4.25: Add link_type, link_label, icon_attachment_id to mbs_buy_links.
 *
 * @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_25 implements MBS_Migration { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Return the migration version string.
	 *
	 * @return string
	 * @since 1.4.0
	 */
	public function version(): string {
		return '4.25';
	}

	/**
	 * Run the migration.
	 *
	 * Uses dbDelta() against the updated MBS_DB_Schema::buy_links() DDL.
	 * dbDelta adds columns present in the DDL but absent from the live table;
	 * existing rows receive the column DEFAULT values automatically.
	 *
	 * @return void
	 * @since 1.4.0
	 */
	public function up(): void {
		global $wpdb;
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		$table           = $wpdb->prefix . 'mbs_buy_links';
		$charset_collate = $wpdb->get_charset_collate();

		// Step 1: Add link_type, link_label, icon_attachment_id columns via dbDelta.
		dbDelta( MBS_DB_Schema::buy_links( $table, $charset_collate ) );

		// Step 2: Backfill — mark existing goodreads/storygraph/bookbub rows as
		// link_type = 'platform'. dbDelta set all existing rows to 'buy' via DEFAULT.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery -- DAO layer -- direct DB access is intentional per MBS architecture
			$wpdb->prepare(
				"UPDATE {$table}
				 SET link_type = 'platform'
				 WHERE retailer_key IN ('goodreads', 'storygraph', 'bookbub')
				   AND is_deleted = 0
				   AND link_type = %s",
				'buy'
			)
		);
	}
}
