<?php
/**
 * Database migrations for the safe event cache.
 *
 * @package VoidPulse
 */

namespace VoidPulse\Infrastructure;

defined( 'ABSPATH' ) || exit;

final class Migrations {
	/**
	 * Create or update the event cache table.
	 *
	 * @return void
	 */
	public static function run() {
		global $wpdb;

		if ( get_option( 'voidpulse_schema_version' ) === VOIDPULSE_SCHEMA_VERSION ) {
			return;
		}

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		$charset    = $wpdb->get_charset_collate();
		$events     = $wpdb->prefix . 'voidpulse_events';
		$sql        = "CREATE TABLE {$events} (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			source varchar(32) NOT NULL,
			source_record_id varchar(191) NOT NULL,
			event_type varchar(32) NOT NULL,
			product_id bigint(20) unsigned NOT NULL DEFAULT 0,
			variation_id bigint(20) unsigned NOT NULL DEFAULT 0,
			event_timestamp datetime NOT NULL,
			payload longtext NOT NULL,
			privacy_level varchar(20) NOT NULL DEFAULT 'safe-v1',
			expires_at datetime NOT NULL,
			created_at datetime NOT NULL,
			PRIMARY KEY  (id),
			UNIQUE KEY source_record (source,source_record_id),
			KEY event_time (event_type,event_timestamp),
			KEY product_id (product_id),
			KEY expires_at (expires_at)
		) {$charset};";

		dbDelta( $sql );
		update_option( 'voidpulse_schema_version', VOIDPULSE_SCHEMA_VERSION, false );
	}
}
