<?php
/**
 * Migration 020: Remove Redundant Fields from RSS Articles
 *
 * Removes fields that are redundant or no longer needed:
 * - article_status: Duplicates import_status, causes confusion
 * - has_cover_image: Not used by current implementation
 * - article_created_at: Duplicates discovered_at
 *
 * Note: This migration is OPTIONAL and can be skipped if backward
 * compatibility with old code is required. The Strategic Plan
 * marks this as "conditional" - run only if codebase audit confirms
 * these fields are truly unused.
 *
 * IMPORTANT: Before running this migration, verify:
 * 1. No code references article_status except as fallback
 * 2. No code references has_cover_image
 * 3. No code references article_created_at except as fallback to discovered_at
 *
 * @package Wisewand
 * @since 2.1.5
 * @license GPL-2.0-or-later
 */

namespace Wisewand\Database\Migrations;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Migration class for removing redundant fields
 *
 * @since 2.1.5
 */
class Migration_020_Remove_Redundancies {

	/**
	 * Run the migration
	 *
	 * SAFETY: This migration is conservative. It will check if the column
	 * exists before attempting to drop it, preventing errors on repeated runs.
	 *
	 * @since 2.1.5
	 * @global wpdb $wpdb WordPress database abstraction object.
	 * @return bool True if migration ran successfully or already completed.
	 */
	public static function run() {
		global $wpdb;

		$table_name = $wpdb->prefix . 'wisewand_rss_articles';

		// Check if table exists (upgrade scenario only).
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) );

		if ( ! $table_exists ) {
			// Table doesn't exist yet - skip migration (fresh install).
			return true;
		}

		// Check if migration already completed (article_status column should not exist).
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		$article_status_exists = $wpdb->get_results(
			$wpdb->prepare( "SHOW COLUMNS FROM `{$table_name}` LIKE %s", 'article_status' )
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		if ( empty( $article_status_exists ) ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'Wisewand: Migration 20 already completed (article_status column does not exist)' );
			}
			return true;
		}

		// Migration needed.
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( 'Wisewand: Starting Migration 20 - Removing redundant fields from RSS articles' );
		}

		// Drop redundant columns (if they exist).
		$columns_to_drop = array();

		// Check each column individually before dropping.
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		if ( ! empty( $wpdb->get_results( $wpdb->prepare( "SHOW COLUMNS FROM `{$table_name}` LIKE %s", 'article_status' ) ) ) ) {
			$columns_to_drop[] = 'DROP COLUMN article_status';
		}

		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		if ( ! empty( $wpdb->get_results( $wpdb->prepare( "SHOW COLUMNS FROM `{$table_name}` LIKE %s", 'has_cover_image' ) ) ) ) {
			$columns_to_drop[] = 'DROP COLUMN has_cover_image';
		}

		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		if ( ! empty( $wpdb->get_results( $wpdb->prepare( "SHOW COLUMNS FROM `{$table_name}` LIKE %s", 'article_created_at' ) ) ) ) {
			$columns_to_drop[] = 'DROP COLUMN article_created_at';
		}
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		if ( empty( $columns_to_drop ) ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'Wisewand: Migration 20 - No columns to drop (already removed)' );
			}
			return true;
		}

		// Build ALTER TABLE query.
		$alter_query = "ALTER TABLE `{$table_name}` " . implode( ', ', $columns_to_drop );

		// Execute drop columns.
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		$result = $wpdb->query( $alter_query );
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		if ( $wpdb->last_error ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'Wisewand: Migration 20 error: ' . $wpdb->last_error );
			}
			return false;
		}

		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( 'Wisewand: Migration 20 completed successfully - Removed ' . count( $columns_to_drop ) . ' redundant columns' );
			error_log( 'Wisewand: Database schema now cleaner and more maintainable' );
		}

		return $result !== false;
	}

	/**
	 * Rollback the migration
	 *
	 * Restores the dropped columns with default values.
	 * Note: Original data is lost and cannot be restored.
	 *
	 * @since 2.1.5
	 * @global wpdb $wpdb WordPress database abstraction object.
	 * @return bool True if rollback succeeded.
	 */
	public static function rollback() {
		global $wpdb;

		$table_name = $wpdb->prefix . 'wisewand_rss_articles';

		// Check if table exists.
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) );

		if ( ! $table_exists ) {
			return true;
		}

		// Re-add columns (if they don't exist).
		$columns_to_add = array();

		// Check each column individually before adding.
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		if ( empty( $wpdb->get_results( $wpdb->prepare( "SHOW COLUMNS FROM `{$table_name}` LIKE %s", 'article_status' ) ) ) ) {
			$columns_to_add[] = "ADD COLUMN article_status VARCHAR(50) DEFAULT 'unknown' COMMENT '(Legacy) Article status from Wisewand API'";
		}

		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		if ( empty( $wpdb->get_results( $wpdb->prepare( "SHOW COLUMNS FROM `{$table_name}` LIKE %s", 'has_cover_image' ) ) ) ) {
			$columns_to_add[] = "ADD COLUMN has_cover_image TINYINT(1) DEFAULT 0 COMMENT '(Legacy) Whether article has cover image'";
		}

		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		if ( empty( $wpdb->get_results( $wpdb->prepare( "SHOW COLUMNS FROM `{$table_name}` LIKE %s", 'article_created_at' ) ) ) ) {
			$columns_to_add[] = "ADD COLUMN article_created_at DATETIME NULL COMMENT '(Legacy) Article creation date from Wisewand'";
		}
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		if ( empty( $columns_to_add ) ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'Wisewand: Migration 20 rollback - No columns to add (already exist)' );
			}
			return true;
		}

		// Build ALTER TABLE query.
		$alter_query = "ALTER TABLE `{$table_name}` " . implode( ', ', $columns_to_add );

		// Execute add columns.
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		$wpdb->query( $alter_query );
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			if ( $wpdb->last_error ) {
				error_log( 'Wisewand: Migration 20 rollback error: ' . $wpdb->last_error );
				return false;
			}
			error_log( 'Wisewand: Migration 20 rolled back successfully (columns restored with default values)' );
			error_log( 'Wisewand: WARNING - Original data was not preserved and cannot be restored' );
		}

		return true;
	}
}
