<?php

namespace Limb_Chatbot\Includes\Migrations;

use Limb_Chatbot\Includes\Data_Objects\Setting;
use Limb_Chatbot\Includes\Interfaces\Migration_Interface;
use Limb_Chatbot\Includes\Services\Helper;
use wpdb;

/**
 * Abstract base class for database migrations.
 *
 * Provides common functionality for all migrations including
 * database access and utility methods.
 *
 * @since 1.0.0
 */
abstract class Abstract_Migration implements Migration_Interface {

	/**
	 * WordPress database instance.
	 *
	 * @var wpdb
	 * @since 1.0.0
	 */
	protected $wpdb;

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		global $wpdb;
		$this->wpdb = $wpdb;
	}

	/**
	 * Check if a table exists in the database.
	 *
	 * @param  string  $table_name  Table name to check.
	 *
	 * @return bool True if table exists, false otherwise.
	 * @since 1.0.0
	 */
	protected function table_exists( string $table_name ): bool {
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		return $this->wpdb->get_var(
				$this->wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name )
			) === $table_name;
	}

	/**
	 * Check if a column exists in a table.
	 *
	 * @param  string  $table_name  Table name.
	 * @param  string  $column_name  Column name.
	 *
	 * @return bool True if column exists, false otherwise.
	 * @since 1.0.0
	 */
	protected function column_exists( string $table_name, string $column_name ): bool {
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$column = $this->wpdb->get_results(
			$this->wpdb->prepare(
				"SHOW COLUMNS FROM `{$table_name}` LIKE %s",
				$column_name
			)
		);

		return ! empty( $column );
	}

	/**
	 * Execute dbDelta for schema changes.
	 *
	 * @param  string  $schema  SQL schema statement.
	 *
	 * @return array Results from dbDelta.
	 * @since 1.0.0
	 */
	protected function db_delta( string $schema ): array {
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		return dbDelta( $schema );
	}

	/**
	 * Log migration activity.
	 *
	 * @param  string  $message  Log message.
	 * @param  string  $level  Log level (info, warning, error).
	 *
	 * @return void
	 * @since 1.0.0
	 */
	protected function log( string $message, string $level = 'info' ): void {
		if ( function_exists( 'error_log' ) && defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			Helper::log( sprintf( '[LBAIC Migration %s] %s: %s',
				$this->get_version(),
				strtoupper( $level ),
				$message ) );
		}
	}

	protected function maybe_add_setting( $key, $value ) {
		if ( ! Setting::exists( $key ) ) {
			Setting::create( [ 'key' => $key, 'value' => $value ] );
		}
	}
}

