<?php

namespace WPSN\Modules\Redirects;

defined('ABSPATH') || exit;

/**
 * Creates/updates custom DB tables for the Redirects module.
 */
final class RedirectsInstaller
{
    // 1.1.0: add redirect migration report tables.
    private const DB_VERSION = '1.1.0';

    public static function maybeInstall(): void
    {
        $installed = (string) get_option('wpsn_redirects_db_version', '');
        if ($installed === self::DB_VERSION) {
            return;
        }

        self::install();
    }

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

        // Ensure settings exist.
        if (get_option(RedirectsSettingsRepository::OPTION_NAME) === false) {
            add_option(RedirectsSettingsRepository::OPTION_NAME, (new RedirectsSettingsRepository())->defaults());
        }

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

        $charset = $wpdb->get_charset_collate();

        $tableRedirects = $wpdb->prefix . 'wpsn_redirects';
        $table404 = $wpdb->prefix . 'wpsn_404_log';

        // Redirect migration: run summaries + skipped/unsupported/error items.
        $tableMigRuns  = $wpdb->prefix . 'wpsn_redirect_migration_runs';
        $tableMigItems = $wpdb->prefix . 'wpsn_redirect_migration_items';

        // Redirect rules.
        // match_type: exact|prefix
        $sql1 = "CREATE TABLE {$tableRedirects} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            from_url varchar(255) NOT NULL,
            to_url varchar(255) DEFAULT NULL,
            match_type varchar(20) NOT NULL DEFAULT 'exact',
            status_code smallint(5) unsigned NOT NULL DEFAULT 301,
            enabled tinyint(1) NOT NULL DEFAULT 1,
            hits bigint(20) unsigned NOT NULL DEFAULT 0,
            last_hit datetime DEFAULT NULL,
            created_at datetime NOT NULL,
            updated_at datetime NOT NULL,
            PRIMARY KEY  (id),
            KEY enabled (enabled),
            KEY match_type (match_type),
            KEY from_url (from_url(191))
        ) {$charset};";

        // 404 log (unique by URL).
        $sql2 = "CREATE TABLE {$table404} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            url varchar(255) NOT NULL,
            hits bigint(20) unsigned NOT NULL DEFAULT 1,
            first_seen datetime NOT NULL,
            last_seen datetime NOT NULL,
            last_referrer varchar(255) DEFAULT NULL,
            last_user_agent varchar(255) DEFAULT NULL,
            PRIMARY KEY  (id),
            UNIQUE KEY url (url(191)),
            KEY last_seen (last_seen)
        ) {$charset};";

        // Redirect migration runs (summary).
        $sql3 = "CREATE TABLE {$tableMigRuns} (
            job_id varchar(36) NOT NULL,
            source varchar(32) NOT NULL,
            overwrite tinyint(1) NOT NULL DEFAULT 0,
            include_disabled tinyint(1) NOT NULL DEFAULT 0,
            total int(11) NOT NULL DEFAULT 0,
            processed int(11) NOT NULL DEFAULT 0,
            imported int(11) NOT NULL DEFAULT 0,
            updated int(11) NOT NULL DEFAULT 0,
            skipped int(11) NOT NULL DEFAULT 0,
            unsupported int(11) NOT NULL DEFAULT 0,
            disabled int(11) NOT NULL DEFAULT 0,
            errors int(11) NOT NULL DEFAULT 0,
            last_error text NULL,
            started_at datetime NOT NULL,
            finished_at datetime DEFAULT NULL,
            PRIMARY KEY  (job_id),
            KEY source (source),
            KEY started_at (started_at)
        ) {$charset};";

        // Redirect migration items (skipped/unsupported/errors).
        $sql4 = "CREATE TABLE {$tableMigItems} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            job_id varchar(36) NOT NULL,
            source varchar(32) NOT NULL,
            reason varchar(64) NOT NULL,
            from_url varchar(255) NOT NULL,
            to_url varchar(255) DEFAULT NULL,
            match_type varchar(20) NOT NULL DEFAULT '',
            status_code smallint(5) unsigned NOT NULL DEFAULT 0,
            enabled tinyint(1) NOT NULL DEFAULT 0,
            raw longtext NULL,
            created_at datetime NOT NULL,
            PRIMARY KEY  (id),
            KEY job_id (job_id),
            KEY reason (reason),
            KEY source (source)
        ) {$charset};";

        dbDelta($sql1);
        dbDelta($sql2);
        dbDelta($sql3);
        dbDelta($sql4);

        update_option('wpsn_redirects_db_version', self::DB_VERSION);
    }
}
