<?php
/**
 * Database schema installer and migrator.
 *
 * @package RewindBrevoFormBridge
 */

namespace RewindBrevoFormBridge;

defined( 'ABSPATH' ) || exit;

/**
 * Creates and upgrades the rbfb_ tables via dbDelta().
 *
 * Lives at the includes/ root (not in a subfolder of the CLAUDE.md tree)
 * because it is infrastructure the bootstrap needs before the container
 * exists.
 *
 * @since 0.1.0
 */
class Schema {

	/**
	 * Install or upgrade all tables, then record the schema version.
	 *
	 * @since 0.1.0
	 * @return void
	 */
	public static function install(): void {
		global $wpdb;

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

		$charset_collate = $wpdb->get_charset_collate();

		$feeds   = $wpdb->prefix . 'rbfb_feeds';
		$log     = $wpdb->prefix . 'rbfb_log';
		$consent = $wpdb->prefix . 'rbfb_consent';

		// dbDelta is strict about formatting: two spaces after PRIMARY KEY,
		// one field per line, keys declared inline.
		$sql = array();

		$sql[] = "CREATE TABLE {$feeds} (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			adapter VARCHAR(50) NOT NULL,
			form_id VARCHAR(191) NOT NULL,
			title VARCHAR(191) NOT NULL,
			status VARCHAR(20) NOT NULL DEFAULT 'active',
			config LONGTEXT NOT NULL,
			created_at DATETIME NOT NULL,
			updated_at DATETIME NOT NULL,
			PRIMARY KEY  (id),
			KEY adapter_form (adapter, form_id(100))
		) {$charset_collate};";

		$sql[] = "CREATE TABLE {$log} (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			feed_id BIGINT UNSIGNED NOT NULL,
			entry_ref VARCHAR(191) NULL,
			email VARCHAR(191) NULL,
			status VARCHAR(20) NOT NULL,
			http_code SMALLINT NULL,
			error_code VARCHAR(60) NULL,
			message TEXT NULL,
			request LONGTEXT NULL,
			response LONGTEXT NULL,
			attempts TINYINT NOT NULL DEFAULT 0,
			created_at DATETIME NOT NULL,
			updated_at DATETIME NOT NULL,
			PRIMARY KEY  (id),
			KEY feed_status (feed_id, status),
			KEY created (created_at)
		) {$charset_collate};";

		$sql[] = "CREATE TABLE {$consent} (
			id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			log_id BIGINT UNSIGNED NOT NULL,
			email VARCHAR(191) NOT NULL,
			consent_text TEXT NOT NULL,
			source_url VARCHAR(255) NULL,
			ip VARCHAR(45) NULL,
			created_at DATETIME NOT NULL,
			PRIMARY KEY  (id),
			KEY email (email)
		) {$charset_collate};";

		foreach ( $sql as $statement ) {
			dbDelta( $statement );
		}

		update_option( 'rbfb_db_version', RBFB_DB_VERSION, false );
	}

	/**
	 * Re-run the installer when the stored schema version is behind.
	 *
	 * Called on plugins_loaded. dbDelta() is idempotent, so re-running the
	 * CREATE TABLE statements is the migration mechanism.
	 *
	 * @since 0.1.0
	 * @return void
	 */
	public static function maybe_upgrade(): void {
		$installed = get_option( 'rbfb_db_version', '' );

		if ( RBFB_DB_VERSION === $installed ) {
			return;
		}

		self::install();
	}
}
