<?php

namespace WPSN\Modules\Privacy;

defined('ABSPATH') || exit;

final class PrivacyInstaller
{
    private const DB_VERSION = 1;
    private const OPTION_NAME = 'wpsn_privacy_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';

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

        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        $sql = "CREATE TABLE {$table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            service varchar(32) NOT NULL DEFAULT '',
            context varchar(64) NOT NULL DEFAULT '',
            method varchar(10) NOT NULL DEFAULT '',
            url text NULL,
            response_code smallint(6) NOT NULL DEFAULT 0,
            error text NULL,
            request_bytes int(11) NOT NULL DEFAULT 0,
            created_at datetime NOT NULL,
            PRIMARY KEY  (id),
            KEY created_at (created_at),
            KEY service_created (service, created_at),
            KEY code_created (response_code, created_at)
        ) {$charset};";

        dbDelta($sql);

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