<?php

namespace classes;

/**
 * Ensures additive schema for e-conomic transfer queue jobs.
 */
class economic_transfer_queue_schema_bootstrap
{
    private static bool $initialized = false;

    public static function ensureTables(): void
    {
        if (self::$initialized) {
            return;
        }

        global $db;

        $db->query(
            "CREATE TABLE IF NOT EXISTS economic_transfer_queue_jobs (
                id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                transfer_type VARCHAR(64) NOT NULL,
                payload_json JSON NOT NULL,
                status VARCHAR(32) NOT NULL DEFAULT 'QUEUED',
                progress_percent TINYINT UNSIGNED NOT NULL DEFAULT 0,
                progress_message VARCHAR(255) NULL,
                attempts INT NOT NULL DEFAULT 0,
                max_attempts INT NOT NULL DEFAULT 3,
                error_message TEXT NULL,
                result_json JSON NULL,
                created_by INT NULL,
                started_at DATETIME NULL,
                completed_at DATETIME NULL,
                next_retry_at DATETIME NULL,
                locked_at DATETIME NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_economic_transfer_queue_jobs_status_created (status, created_at),
                INDEX idx_economic_transfer_queue_jobs_next_retry (next_retry_at),
                INDEX idx_economic_transfer_queue_jobs_transfer_type (transfer_type)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
        );

        $db->query(
            "CREATE TABLE IF NOT EXISTS economic_transfer_queue_job_dismissals (
                queue_job_id BIGINT UNSIGNED NOT NULL,
                user_id INT NOT NULL,
                dismissed_status VARCHAR(32) NOT NULL,
                dismissed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY (queue_job_id, user_id),
                INDEX idx_economic_transfer_queue_job_dismissals_user_status (user_id, dismissed_status),
                INDEX idx_economic_transfer_queue_job_dismissals_job (queue_job_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
        );

        self::$initialized = true;
    }
}
