<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Arcai_Activator {

	public static function activate() {
		self::create_tables();
		update_option( 'arcai_db_version', ARCAI_VERSION );

		if ( false === get_option( 'arcai_settings', false ) ) {
			add_option( 'arcai_settings', Arcai_Settings::defaults() );
		}
	}

	public static function deactivate() {
		wp_clear_scheduled_hook( 'arcai_process_batch' );
	}

	public static function maybe_upgrade() {
		if ( get_option( 'arcai_db_version' ) !== ARCAI_VERSION ) {
			self::create_tables();
			update_option( 'arcai_db_version', ARCAI_VERSION );
		}
	}

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

		$charset_collate = $wpdb->get_charset_collate();

		$chunks = "CREATE TABLE {$wpdb->prefix}arcai_chunks (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			post_id BIGINT UNSIGNED NOT NULL,
			chunk_index SMALLINT UNSIGNED NOT NULL DEFAULT 0,
			content LONGTEXT NOT NULL,
			embedding LONGBLOB NULL,
			token_count INT UNSIGNED NOT NULL DEFAULT 0,
			post_date DATETIME NOT NULL,
			PRIMARY KEY  (id),
			KEY post_id (post_id),
			KEY post_date (post_date)
		) $charset_collate;";

		$usage = "CREATE TABLE {$wpdb->prefix}arcai_usage (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			created_at DATETIME NOT NULL,
			event_type VARCHAR(32) NOT NULL,
			tokens_in INT UNSIGNED NOT NULL DEFAULT 0,
			tokens_out INT UNSIGNED NOT NULL DEFAULT 0,
			cost DECIMAL(12,6) NOT NULL DEFAULT 0,
			PRIMARY KEY  (id),
			KEY created_at (created_at)
		) $charset_collate;";

		dbDelta( $chunks );
		dbDelta( $usage );
	}
}
