<?php
/**
 * Database schema.
 *
 * @package WPDudeProducts
 */

declare(strict_types=1);

namespace WPDude\Products\Database;

/**
 * Creates plugin tables.
 */
final class Migrator {

	public const OPTION_KEY = 'wpdude_dc_db_version';
	public const DB_VERSION = '4';

	/**
	 * Install / upgrade on activation and boot.
	 */
	public static function install(): void {
		self::create_tables();
		update_option( self::OPTION_KEY, self::DB_VERSION, false );
	}

	/**
	 * Upgrade when version changes.
	 */
	public static function maybe_upgrade(): void {
		$installed = (string) get_option( self::OPTION_KEY, '' );
		if ( $installed === self::DB_VERSION ) {
			return;
		}
		self::install();
	}

	/**
	 * Create plugin tables.
	 */
	private static function create_tables(): void {
		global $wpdb;

		$charset    = $wpdb->get_charset_collate();
		$events     = $wpdb->prefix . 'wpdude_dc_stripe_events';
		$tokens     = $wpdb->prefix . 'wpdude_dc_order_tokens';
		$deliveries = $wpdb->prefix . 'wpdude_dc_webhook_deliveries';

		$sql_events = "CREATE TABLE {$events} (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			event_id varchar(255) NOT NULL,
			event_type varchar(100) NOT NULL DEFAULT '',
			processed_at datetime NOT NULL,
			PRIMARY KEY  (id),
			UNIQUE KEY event_id (event_id)
		) {$charset};";

		$sql_tokens = "CREATE TABLE {$tokens} (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			order_id bigint(20) unsigned NOT NULL,
			token_hash char(64) NOT NULL,
			expires_at datetime NOT NULL,
			created_at datetime NOT NULL,
			PRIMARY KEY  (id),
			UNIQUE KEY token_hash (token_hash),
			KEY order_id (order_id)
		) {$charset};";

		$sql_deliveries = "CREATE TABLE {$deliveries} (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			event_id char(36) NOT NULL,
			event_type varchar(64) NOT NULL DEFAULT '',
			order_uuid char(36) NOT NULL DEFAULT '',
			payload longtext NOT NULL,
			status varchar(16) NOT NULL DEFAULT 'pending',
			attempts int(11) NOT NULL DEFAULT 0,
			response_code int(11) NOT NULL DEFAULT 0,
			last_error text NULL,
			next_retry_at datetime NULL,
			delivered_at datetime NULL,
			created_at datetime NOT NULL,
			updated_at datetime NOT NULL,
			PRIMARY KEY  (id),
			UNIQUE KEY event_id (event_id),
			KEY status_retry (status, next_retry_at),
			KEY order_uuid (order_uuid),
			KEY created_at (created_at)
		) {$charset};";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta( $sql_events );
		dbDelta( $sql_tokens );
		dbDelta( $sql_deliveries );
	}
}
