<?php

namespace WPSN\Modules\Revisions;

defined('ABSPATH') || exit;

/**
 * Creates/updates custom DB table for unified revisions/undo.
 */
final class RevisionsInstaller
{
    private const DB_VERSION = '1.0.0';

    public static function maybeInstall(): void
    {
        $installed = (string) get_option('wpsn_revisions_db_version', '');
        if ($installed === self::DB_VERSION) {
            return;
        }

        self::install();
    }

    public static function install(): void
    {
        global $wpdb;

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

        $charset = $wpdb->get_charset_collate();
        $table = $wpdb->prefix . 'wpsn_revisions';

        $sql = "CREATE TABLE {$table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            object_type varchar(20) NOT NULL,
            object_id bigint(20) unsigned NOT NULL DEFAULT 0,
            object_subtype varchar(64) NOT NULL DEFAULT '',
            action varchar(32) NOT NULL DEFAULT 'update',
            source varchar(32) NOT NULL DEFAULT '',
            actor_user_id bigint(20) unsigned NOT NULL DEFAULT 0,
            before_json longtext DEFAULT NULL,
            after_json longtext DEFAULT NULL,
            meta_json longtext DEFAULT NULL,
            created_at datetime NOT NULL,
            rolled_back_at datetime DEFAULT NULL,
            rolled_back_by bigint(20) unsigned NOT NULL DEFAULT 0,
            PRIMARY KEY  (id),
            KEY object (object_type, object_id),
            KEY created_at (created_at),
            KEY source (source),
            KEY actor_user_id (actor_user_id)
        ) {$charset};";

        dbDelta($sql);

        update_option('wpsn_revisions_db_version', self::DB_VERSION, false);
    }
}
