<?php
/**
 * Migration: Create Knowledge Chunks Table
 *
 * Creates a table for chunk-level semantic indexing (embeddings).
 *
 * @package BoostBot
 * @since   1.7.0
 */

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

/**
 * Class BoostBot_Migration_Create_Knowledge_Chunks_Table
 *
 * @since 1.7.0
 */
class BoostBot_Migration_Create_Knowledge_Chunks_Table {

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

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

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

        // Create table via dbDelta for schema management.
        $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,
            knowledge_id bigint(20) unsigned NOT NULL,
            content_type varchar(50) NOT NULL,
            content_id bigint(20) unsigned DEFAULT NULL,
            chunk_index int(11) NOT NULL DEFAULT 0,
            chunk_text longtext DEFAULT NULL,
            embedding_vector longtext DEFAULT NULL,
            embedding_provider varchar(20) DEFAULT NULL,
            embedding_model varchar(100) DEFAULT NULL,
            embedding_dimension int(11) DEFAULT NULL,
            char_count int(11) DEFAULT 0,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_knowledge_id (knowledge_id),
            KEY idx_content (content_type, content_id),
            KEY idx_updated_at (updated_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;
    }
}


