<?php
/**
 * Activator — creates custom tables and seeds default options.
 *
 * @package WPLens
 */

namespace WPLens;

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

final class Activator {

	public static function activate(): void {
		self::create_tables();
		self::seed_options();
		self::schedule_crons();
		flush_rewrite_rules();

		// Arm the welcome wizard for the next admin page load.
		if ( ! get_option( 'wplens_setup_complete' ) ) {
			\WPLens\Admin\Welcome::arm_redirect();
		}
	}

	private static function create_tables(): void {
		global $wpdb;
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		$charset_collate = $wpdb->get_charset_collate();
		$prefix          = $wpdb->prefix;

		$sql = array();

		$sql[] = "CREATE TABLE {$prefix}wplens_crawler_log (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			visited_at DATETIME NOT NULL,
			bot_slug VARCHAR(64) NOT NULL,
			bot_family VARCHAR(32) NOT NULL,
			user_agent VARCHAR(512) NOT NULL,
			request_uri VARCHAR(2048) NOT NULL,
			request_method VARCHAR(8) NOT NULL DEFAULT 'GET',
			response_code SMALLINT UNSIGNED NOT NULL DEFAULT 200,
			ip_hash CHAR(64) NOT NULL,
			post_id BIGINT UNSIGNED DEFAULT NULL,
			PRIMARY KEY (id),
			KEY idx_visited_at (visited_at),
			KEY idx_bot_slug (bot_slug),
			KEY idx_post_id (post_id)
		) {$charset_collate};";

		$sql[] = "CREATE TABLE {$prefix}wplens_scans (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			post_id BIGINT UNSIGNED NOT NULL,
			scan_type VARCHAR(32) NOT NULL,
			ai_provider VARCHAR(32) DEFAULT NULL,
			score TINYINT UNSIGNED DEFAULT NULL,
			findings LONGTEXT NOT NULL,
			created_at DATETIME NOT NULL,
			PRIMARY KEY (id),
			KEY idx_post_id_created (post_id, created_at),
			KEY idx_created_at (created_at)
		) {$charset_collate};";

		$sql[] = "CREATE TABLE {$prefix}wplens_citation_queries (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			query VARCHAR(512) NOT NULL,
			is_active TINYINT(1) NOT NULL DEFAULT 1,
			created_at DATETIME NOT NULL,
			PRIMARY KEY (id),
			KEY idx_active (is_active)
		) {$charset_collate};";

		$sql[] = "CREATE TABLE {$prefix}wplens_citation_checks (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			query_id BIGINT UNSIGNED NOT NULL,
			ai_provider VARCHAR(32) NOT NULL,
			cited TINYINT(1) NOT NULL DEFAULT 0,
			position SMALLINT UNSIGNED DEFAULT NULL,
			cited_url VARCHAR(2048) DEFAULT NULL,
			raw_response_excerpt TEXT,
			checked_at DATETIME NOT NULL,
			PRIMARY KEY (id),
			KEY idx_query_provider_checked (query_id, ai_provider, checked_at)
		) {$charset_collate};";

		foreach ( $sql as $statement ) {
			dbDelta( $statement );
		}

		update_option( 'wplens_db_version', WPLENS_DB_VERSION );
	}

	private static function seed_options(): void {
		if ( false === get_option( 'wplens_settings' ) ) {
			add_option( 'wplens_settings', \WPLens\Utils\Options::defaults() );
		}

		// Per-site IP salt — one-time generated, never rotated.
		if ( false === get_option( 'wplens_ip_salt' ) ) {
			add_option( 'wplens_ip_salt', wp_generate_password( 64, false, false ) );
		}

		// Target domain for citation tracking — derived from home_url().
		$settings = get_option( 'wplens_settings', array() );
		if ( empty( $settings['citations']['target_domain'] ) ) {
			$host = wp_parse_url( home_url(), PHP_URL_HOST );
			if ( $host ) {
				$settings['citations']['target_domain'] = $host;
				update_option( 'wplens_settings', $settings );
			}
		}

		if ( false === get_option( 'wplens_setup_complete' ) ) {
			add_option( 'wplens_setup_complete', false );
		}

		// Default schema OFF when a conflicting SEO plugin is active.
		if ( \WPLens\Schema\ConflictDetector::has_conflict() ) {
			$settings = get_option( 'wplens_settings', array() );
			if ( is_array( $settings ) ) {
				$settings['schema']['enabled'] = false;
				update_option( 'wplens_settings', $settings );
			}
		}
	}

	private static function schedule_crons(): void {
		if ( ! wp_next_scheduled( 'wplens_cron_log_pruner' ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'wplens_cron_log_pruner' );
		}
		if ( ! wp_next_scheduled( 'wplens_cron_weekly_report' ) ) {
			wp_schedule_event( strtotime( 'next Monday 09:00' ), 'weekly', 'wplens_cron_weekly_report' );
		}
	}
}
