<?php

namespace WPSN\Modules\AIReadiness;

defined('ABSPATH') || exit;

final class PolicyLogInstaller
{
    private const DB_VERSION = 1;
    private const OPTION_NAME = 'wpsn_policy_log_db_version';

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

        self::install();
    }

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

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

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

        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        $sql = "CREATE TABLE {$table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            context varchar(32) NOT NULL,
            action varchar(32) NOT NULL,
            message text NULL,
            user_id bigint(20) unsigned NULL,
            old_value longtext NULL,
            new_value longtext NULL,
            created_at datetime NOT NULL,
            PRIMARY KEY  (id),
            KEY context_created (context, created_at),
            KEY action_created (action, created_at),
            KEY created_at (created_at)
        ) {$charset};";

        dbDelta($sql);

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