<?php

namespace WPSN\Modules\ActivityLog;

defined('ABSPATH') || exit;

final class ActivityLogInstaller
{
    private const OPTION_NAME = 'wpsn_activity_log_db_version';
    private const CURRENT_VERSION = '1';

    public static function maybeInstall(): void
    {
        $v = get_option(self::OPTION_NAME, '');
        $v = is_string($v) ? $v : '';
        if ($v === self::CURRENT_VERSION) {
            return;
        }

        self::install();
        update_option(self::OPTION_NAME, self::CURRENT_VERSION, false);
    }

    public static function install(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'wpsn_activity_log';

        $charset = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE {$table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            created_at datetime NOT NULL,
            user_id bigint(20) unsigned NULL,
            action varchar(80) NOT NULL,
            context varchar(80) NOT NULL DEFAULT '',
            object_type varchar(30) NOT NULL DEFAULT '',
            object_id bigint(20) unsigned NULL,
            object_key varchar(191) NOT NULL DEFAULT '',
            message text NOT NULL,
            meta longtext NULL,
            PRIMARY KEY  (id),
            KEY created_at (created_at),
            KEY action (action),
            KEY object (object_type, object_id),
            KEY user_id (user_id)
        ) {$charset};";

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