<?php

namespace ConflictRadar\Core;

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

/**
 * Runs on register_activation_hook. Creates tables, sets default options, registers cron jobs.
 */
class Activator {

	public static function activate(): void {
		self::createTables();
		self::setDefaultOptions();
		self::scheduleCronJobs();
	}

	private static function createTables(): void {
		global $wpdb;

		$charset_collate = $wpdb->get_charset_collate();

		$sql_events = "CREATE TABLE {$wpdb->prefix}conflict_radar_events (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  event_type varchar(50) NOT NULL,
  plugin_slug varchar(191) NOT NULL DEFAULT '',
  plugin_name varchar(191) NOT NULL DEFAULT '',
  version_from varchar(50) NOT NULL DEFAULT '',
  version_to varchar(50) NOT NULL DEFAULT '',
  update_source varchar(20) NOT NULL DEFAULT 'manual',
  triggered_by_user bigint(20) unsigned NOT NULL DEFAULT 0,
  snapshot_data longtext DEFAULT NULL,
  correlation_id bigint(20) unsigned NOT NULL DEFAULT 0,
  created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY  (id),
  KEY event_type (event_type),
  KEY plugin_slug (plugin_slug),
  KEY created_at (created_at),
  KEY correlation_id (correlation_id)
) $charset_collate;";

		$sql_logs = "CREATE TABLE {$wpdb->prefix}conflict_radar_logs (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  error_type varchar(20) NOT NULL,
  error_message text NOT NULL,
  error_file varchar(500) NOT NULL DEFAULT '',
  error_line int(11) unsigned NOT NULL DEFAULT 0,
  raw_entry text NOT NULL,
  log_hash char(32) NOT NULL DEFAULT '',
  event_correlation_id bigint(20) unsigned NOT NULL DEFAULT 0,
  correlation_confidence varchar(10) NOT NULL DEFAULT '',
  logged_at datetime NOT NULL,
  created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY  (id),
  UNIQUE KEY log_hash (log_hash),
  KEY error_type (error_type),
  KEY logged_at (logged_at),
  KEY created_at (created_at),
  KEY event_correlation_id (event_correlation_id)
) $charset_collate;";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta( $sql_events );
		dbDelta( $sql_logs );
	}

	private static function setDefaultOptions(): void {
		add_option( 'conflict_radar_version', '1.0.0' );
		add_option( 'conflict_radar_db_version', '1.0' );
		add_option( 'conflict_radar_log_path', '' );
		add_option( 'conflict_radar_retention_days', 90 );
		add_option( 'conflict_radar_last_log_pointer', 0 );
	}

	private static function scheduleCronJobs(): void {
		if ( ! wp_next_scheduled( 'conflict_radar_scan_logs' ) ) {
			wp_schedule_event( time(), 'hourly', 'conflict_radar_scan_logs' );
		}

		if ( ! wp_next_scheduled( 'conflict_radar_purge_old_data' ) ) {
			wp_schedule_event( time(), 'weekly', 'conflict_radar_purge_old_data' );
		}
	}
}
