<?php
/**
 * Migration: Create Index Queue Table
 *
 * Creates a persistent queue table for resilient indexing.
 *
 * @package BoostBot
 * @since   1.13.0
 */

// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Class BoostBot_Migration_Create_Index_Queue_Table
 *
 * @since 1.13.0
 */
class BoostBot_Migration_Create_Index_Queue_Table {

    /**
     * Run the migration.
     *
     * @return bool True on success.
     */
    public static function run(): bool {
        global $wpdb;

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

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        $charset_collate = $wpdb->get_charset_collate();

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $sql = "CREATE TABLE {$table_name} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            content_id bigint(20) unsigned NOT NULL,
            content_type varchar(20) NOT NULL,
            priority tinyint(3) unsigned NOT NULL DEFAULT 5,
            status enum('pending','processing','completed','failed','skipped') NOT NULL DEFAULT 'pending',
            extraction_level tinyint(3) unsigned NOT NULL DEFAULT 5,
            attempts tinyint(3) unsigned NOT NULL DEFAULT 0,
            max_attempts tinyint(3) unsigned NOT NULL DEFAULT 3,
            content_size int(10) unsigned NOT NULL DEFAULT 0,
            last_error longtext DEFAULT NULL,
            memory_peak int(10) unsigned DEFAULT NULL,
            processing_time float DEFAULT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            started_at datetime DEFAULT NULL,
            completed_at datetime DEFAULT NULL,
            PRIMARY KEY (id),
            UNIQUE KEY unique_content (content_id, content_type),
            KEY idx_status_priority (status, priority),
            KEY idx_processing (status, started_at)
        ) {$charset_collate};";

        dbDelta( $sql );

        // Best-effort sanity check.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $exists = $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $table_name ) );

        return (bool) $exists;
    }
}

