<?php
/**
 * Add AI metadata columns to product tags.
 *
 * @package Ugcify
 */

namespace Ugcify\Database\Migrations;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * AlterProductTagsTableAddAIColumns migration class.
 */
class AlterProductTagsTableAddAIColumns {
	/**
	 * WordPress database instance.
	 *
	 * @var \wpdb
	 */
	private $wpdb;

	/**
	 * Constructor.
	 *
	 * @param \wpdb $wpdb WordPress database instance.
	 */
	public function __construct( $wpdb ) {
		$this->wpdb = $wpdb;
	}

	/**
	 * Run migration.
	 *
	 * @return void
	 */
	public function run() {
		$table = $this->wpdb->prefix . 'ugcify_product_tags';

		if ( ! $this->column_exists( $table, 'source' ) ) {
			$this->wpdb->query( "ALTER TABLE {$table} ADD source VARCHAR(20) NOT NULL DEFAULT 'manual' AFTER custom_label" );
		}

		if ( ! $this->column_exists( $table, 'ai_job_id' ) ) {
			$this->wpdb->query( "ALTER TABLE {$table} ADD ai_job_id BIGINT(20) UNSIGNED DEFAULT NULL AFTER source" );
		}

		if ( ! $this->column_exists( $table, 'confidence' ) ) {
			$this->wpdb->query( "ALTER TABLE {$table} ADD confidence FLOAT DEFAULT NULL AFTER ai_job_id" );
		}
	}

	/**
	 * Check if a column exists.
	 *
	 * @param string $table Table name.
	 * @param string $column Column name.
	 * @return bool
	 */
	private function column_exists( string $table, string $column ): bool {
		$result = $this->wpdb->get_var(
			$this->wpdb->prepare(
				"SHOW COLUMNS FROM {$table} LIKE %s",
				$column
			)
		);

		return ! empty( $result );
	}
}
