<?php
/**
 * Database operations for the Context Awareness module.
 *
 * @package Replyan_AI
 */

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

final class Replyan_AI_Context_Awareness_DB {

	/**
	 * Create custom tables for context awareness.
	 */
	public static function create_table(): void {
		global $wpdb;

		$charset_collate = $wpdb->get_charset_collate();
		$table_name      = $wpdb->prefix . 'replyan_ai_knowledge_chunks';

		$sql = "CREATE TABLE {$table_name} (
			id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			post_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
			chunk_index INT(11) NOT NULL DEFAULT 0,
			post_type VARCHAR(255) NOT NULL DEFAULT 'post',
			title VARCHAR(255) NOT NULL DEFAULT '',
			url TEXT NOT NULL,
			content LONGTEXT NOT NULL,
			embedding LONGTEXT NULL,
			token_count INT(11) NOT NULL DEFAULT 0,
			checksum VARCHAR(64) NOT NULL DEFAULT '',
			created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY  (id),
			KEY post_id (post_id),
			KEY chunk_index (chunk_index),
			KEY post_type (post_type)
		) {$charset_collate};";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange
		dbDelta( $sql );
	}
}
