<?php
/**
 * Migration: Per-language global rules — copies unscoped global rules,
 * forbidden topics, and default welcome text to language-scoped options.
 *
 * Existing unscoped values are Hebrew content on all live sites.
 * This migration copies them to the primary language's scoped key
 * (e.g. boostbot_global_rules → boostbot_global_rules_he) so that
 * the new per-language retrieval finds them.
 *
 * The unscoped option is kept as a fallback for safety — consumers
 * check the scoped key first and fall back to unscoped.
 *
 * Idempotent: safe to run multiple times.
 *
 * @package BoostBot
 * @since   1.4.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class BoostBot_Migration_Per_Language_Global_Rules {

	/**
	 * Run the migration.
	 */
	public static function run(): void {
		$flag = get_option( 'boostbot_per_lang_global_rules_migrated', '' );
		if ( '' !== $flag ) {
			return;
		}

		$primary = 'he';
		if ( class_exists( 'BoostBot_Language' ) ) {
			$primary = BoostBot_Language::get_primary() ?: 'he';
		} elseif ( '' !== get_option( 'boostbot_primary_language', '' ) ) {
			$primary = get_option( 'boostbot_primary_language' );
		}

		$keys = array(
			'global_rules',
			'global_forbidden_topics',
			'global_default_welcome_text',
			'brand_card_global_json',
			'brand_card_global_version',
			'service_catalog_overrides_json',
			'service_catalog_overrides_version',
		);

		$prefix = 'boostbot_';

		foreach ( $keys as $key ) {
			$unscoped_value = get_option( $prefix . $key, '' );
			if ( '' === $unscoped_value ) {
				continue;
			}

			$scoped_option = $prefix . $key . '_' . $primary;

			// Only write if the scoped key doesn't already exist.
			if ( false === get_option( $scoped_option ) ) {
				update_option( $scoped_option, $unscoped_value );
			}
		}

		update_option( 'boostbot_per_lang_global_rules_migrated', current_time( 'mysql' ) );
	}
}
