<?php

namespace WPSN\Modules\Stability;

defined('ABSPATH') || exit;

final class SnapshotsInstaller
{
    private const OPTION_NAME = 'wpsn_snapshots_db_version';
    private const DB_VERSION = 1;

    public static function maybeInstall(): void
    {
        $installed = get_option(self::OPTION_NAME, 0);
        $installed = (int) $installed;
        if ($installed === self::DB_VERSION) {
            return;
        }

        self::install();

        update_option(self::OPTION_NAME, self::DB_VERSION, false);
    }

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

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

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

        $sql = "CREATE TABLE {$table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            type VARCHAR(20) NOT NULL,
            label VARCHAR(191) NOT NULL DEFAULT '',
            user_id BIGINT UNSIGNED NULL,
            plugin_version VARCHAR(32) NOT NULL DEFAULT '',
            created_at DATETIME NOT NULL,
            payload LONGTEXT NOT NULL,
            payload_hash VARCHAR(64) NOT NULL DEFAULT '',
            PRIMARY KEY  (id),
            KEY type_created_at (type, created_at),
            KEY created_at (created_at)
        ) {$charset};";

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange
        dbDelta($sql);
    }
}
