<?php

namespace Limb_Chatbot\Includes\Migrations;

use Limb_Chatbot\Includes\AI_Providers\Open_Router\Open_Router;
use Limb_Chatbot\Includes\AI_Providers\Open_Router\Seeders\AI_Models_Seeder;
use Limb_Chatbot\Includes\Data_Objects\Setting;

/**
 * Migration for version 1.0.15
 *
 * Alters lbaic_user_metas.meta_value from varchar(512) to longtext so that
 * larger values (e.g. device_info JSON) can be stored without database errors.
 *
 * @since 1.0.15
 */
class Migration_1_0_15 extends Abstract_Migration {

	/**
	 * Get the target version this migration upgrades to.
	 *
	 * @return string
	 * @since 1.0.15
	 */
	public function get_version(): string {
		return '1.0.15';
	}

	/**
	 * Get migration description.
	 *
	 * @return string
	 * @since 1.0.15
	 */
	public function get_description(): string {
		return 'Alter lbaic_user_metas.meta_value to longtext and rename vector index meta host to host_1536';
	}

	/**
	 * Execute the migration.
	 *
	 * Alters meta_value column from varchar(512) to longtext so device_info
	 * and other large meta values can be stored without "value too long" errors.
	 * Also renames 'host' meta key to 'host_1536' in vector index metas.
	 *
	 * @return bool True on success, false on failure.
	 * @since 1.0.15
	 */
	public function up(): bool {
		$this->log( 'Starting migration 1.0.15 - Altering lbaic_user_metas.meta_value to longtext' );

		$table_name = $this->wpdb->prefix . 'lbaic_user_metas';

		if ( ! $this->table_exists( $table_name ) ) {
			$this->log( "Table {$table_name} does not exist, skipping" );

			return true;
		}

		if ( ! $this->column_exists( $table_name, 'meta_value' ) ) {
			$this->log( "Column meta_value does not exist in {$table_name}, skipping" );

			return true;
		}

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$result = $this->wpdb->query(
			"ALTER TABLE `{$table_name}` MODIFY COLUMN meta_value longtext NULL"
		);

		if ( $result === false ) {
			$this->log( sprintf( 'Altering table failed: %s', $this->wpdb->last_error ), 'error' );

			return false;
		}

		$this->log( 'Migration 1.0.15 completed successfully - meta_value is now longtext' );

		return true;
	}
}
