<?php

namespace WPSN\Modules\IndexNow;

defined('ABSPATH') || exit;

final class IndexNowInstaller
{
    private const DB_VERSION = 1;
    private const OPTION_NAME = 'wpsn_indexnow_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_indexnow_log';

        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        $sql = "CREATE TABLE {$table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            status varchar(16) NOT NULL DEFAULT 'ok',
            response_code smallint(6) NOT NULL DEFAULT 0,
            url_count int(11) NOT NULL DEFAULT 0,
            endpoint text NULL,
            payload longtext NULL,
            error text NULL,
            created_at datetime NOT NULL,
            PRIMARY KEY  (id),
            KEY created_at (created_at),
            KEY status_created (status, created_at)
        ) {$charset};";

        dbDelta($sql);

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