<?php
// DESCRIPTION: Manages database table creation and schema upgrades for the sync log system.
// Runs on plugin activation and on plugins_loaded to handle upgrades.

namespace SheetWise\Install;

class Installer {

	/**
	 * Current database schema version
	 *
	 * @since 2.0.0
	 *
	 * @var string
	 */
	const DB_VERSION = '1.0.0';

	/**
	 * Run the installer
	 *
	 * Creates or updates database tables if the stored version
	 * is older than the current schema version.
	 *
	 * @since 2.0.0
	 *
	 * @return void
	 */
	public static function run() {
		$installed_version = get_option( 'swise_db_version', '' );

		if ( $installed_version === self::DB_VERSION ) {
			return;
		}

		self::create_tables();

		update_option( 'swise_db_version', self::DB_VERSION );
	}

	/**
	 * Create the sync logs database table
	 *
	 * @since 2.0.0
	 *
	 * @return void
	 */
	public static function create_tables() {
		global $wpdb;

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

		$sql = "CREATE TABLE $table_name (
			id              bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			integration_id  bigint(20) unsigned NOT NULL DEFAULT 0,
			hook            varchar(191)        NOT NULL DEFAULT '',
			status          varchar(20)         NOT NULL DEFAULT 'pending',
			attempts        tinyint(3) unsigned NOT NULL DEFAULT 0,
			error_message   text                NULL,
			error_code      varchar(50)         NULL,
			data_payload    longtext            NULL,
			row_count       int(10) unsigned    NOT NULL DEFAULT 0,
			created_at      datetime            NOT NULL DEFAULT CURRENT_TIMESTAMP,
			updated_at      datetime            NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY  (id),
			KEY idx_integration_id (integration_id),
			KEY idx_status (status),
			KEY idx_created_at (created_at),
			KEY idx_hook (hook)
		) $charset_collate;";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		dbDelta( $sql );
	}

	/**
	 * Get the sync logs table name
	 *
	 * @since 2.0.0
	 *
	 * @return string
	 */
	public static function get_sync_logs_table() {
		global $wpdb;

		return $wpdb->prefix . 'swise_sync_logs';
	}
}
