<?php
/**
 * Migration: Add ai_summary column to conversations table.
 *
 * Stores AI-generated conversation summaries alongside the conversation record
 * for display in the admin panel and cross-referencing with meetings.
 *
 * @package BoostBot
 * @since   1.9.1
 */

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

/**
 * Class BoostBot_Migration_Add_Conversation_Summary
 *
 * @since 1.9.1
 */
class BoostBot_Migration_Add_Conversation_Summary {

    /**
     * Run the migration.
     *
     * @return bool True on success.
     */
    public static function run() {
        return self::up();
    }

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

        $conversations_table = self::sanitize_identifier( $wpdb->prefix . 'boostbot_conversations' );

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table identifier sanitized via sanitize_identifier(); values bind via prepare().
        $col_exists = $wpdb->get_results(
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            $wpdb->prepare(
                "SHOW COLUMNS FROM {$conversations_table} LIKE %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                'ai_summary'
            )
        );

        if ( empty( $col_exists ) ) {
            $wpdb->query( "ALTER TABLE {$conversations_table} ADD COLUMN ai_summary text DEFAULT NULL AFTER duration_seconds" ); // phpcs:ignore
            BoostBot_Logger::info( 'Migration: Added ai_summary column to conversations table.' );
        }

        return true;
    }

    /**
     * Restrict a SQL identifier to [A-Za-z0-9_] characters.
     *
     * DDL cannot use $wpdb->prepare() for identifiers, so any identifier
     * that ends up interpolated into a query first passes through this
     * allow-list.
     *
     * @param string $identifier Raw identifier.
     * @return string Identifier with disallowed characters removed.
     */
    private static function sanitize_identifier( $identifier ) {
        return preg_replace( '/[^A-Za-z0-9_]/', '', (string) $identifier );
    }
}
