<?php

namespace WPSN\Core\Queue;

defined('ABSPATH') || exit;

final class QueueInstaller
{
    // 2: add priority column for better control (audit/backfill jobs can run before low-priority tasks).
    // 3: add composite index for stale-job requeue and large-queue performance.
    private const DB_VERSION = 3;
    private const OPTION_NAME = 'wpsn_queue_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_queue_jobs';
        $charset = $wpdb->get_charset_collate();

        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        $sql = "CREATE TABLE {$table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            job_type varchar(64) NOT NULL,
            priority int(11) NOT NULL DEFAULT 10,
            payload longtext NOT NULL,
            status varchar(20) NOT NULL DEFAULT 'pending',
            attempts int(11) NOT NULL DEFAULT 0,
            run_at datetime NOT NULL,
            locked_at datetime NULL,
            locked_by varchar(64) NULL,
            last_error text NULL,
            created_at datetime NOT NULL,
            updated_at datetime NOT NULL,
            PRIMARY KEY  (id),
            KEY status_priority_run_at (status, priority, run_at),
            KEY locked_at (locked_at),
            KEY status_locked_at (status, locked_at)
        ) {$charset};";

        dbDelta($sql);

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