<?php

namespace WPSN\Modules\IndexationRisk;

defined('ABSPATH') || exit;

final class IndexationRiskInstaller
{
    private const DB_VERSION = '1.0.0';

    public static function maybeInstall(): void
    {
        $installed = (string) get_option('wpsn_indexation_risk_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_indexation_risk';

        $sql = "CREATE TABLE {$table} (
            post_id bigint(20) unsigned NOT NULL,
            post_type varchar(64) NOT NULL DEFAULT '',
            url varchar(255) NOT NULL DEFAULT '',
            title varchar(255) NOT NULL DEFAULT '',
            score int(11) NOT NULL DEFAULT 0,
            inbound_links int(11) NOT NULL DEFAULT 0,
            word_count int(11) NOT NULL DEFAULT 0,
            in_sitemap tinyint(1) NOT NULL DEFAULT 0,
            indexable tinyint(1) NOT NULL DEFAULT 1,
            reasons_json longtext DEFAULT NULL,
            scanned_at datetime NOT NULL,
            updated_at datetime NOT NULL,
            PRIMARY KEY  (post_id),
            KEY score (score),
            KEY post_type (post_type),
            KEY scanned_at (scanned_at)
        ) {$charset};";

        dbDelta($sql);

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