<?php

namespace classes;

class backup_schema_bootstrap
{
    private static bool $initialized = false;

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

        global $db;

        if (!isset($db) || !is_object($db) || !method_exists($db, 'query')) {
            return;
        }

        $db->query(
            "CREATE TABLE IF NOT EXISTS backup_records (
                backup_uuid VARCHAR(64) NOT NULL PRIMARY KEY,
                name VARCHAR(191) NOT NULL,
                description TEXT NULL,
                source VARCHAR(32) NOT NULL DEFAULT 'manual',
                status VARCHAR(32) NOT NULL DEFAULT 'queued',
                schema_version INT UNSIGNED NOT NULL DEFAULT 2,
                storage_bucket VARCHAR(191) NOT NULL DEFAULT 'backups',
                storage_prefix VARCHAR(255) NOT NULL,
                manifest_key VARCHAR(255) NULL,
                manifest_sha256 CHAR(64) NULL,
                encryption_key_id VARCHAR(191) NULL,
                component_count INT UNSIGNED NOT NULL DEFAULT 0,
                object_count INT UNSIGNED NOT NULL DEFAULT 0,
                total_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
                requested_by_user_id INT NULL,
                started_at DATETIME NULL,
                completed_at DATETIME NULL,
                verified_at DATETIME NULL,
                expires_at DATETIME NULL,
                last_error TEXT NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
                KEY idx_backup_records_status_created (status, created_at),
                KEY idx_backup_records_verified (verified_at),
                KEY idx_backup_records_expires (expires_at)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
        );

        $db->query(
            "CREATE TABLE IF NOT EXISTS backup_components (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                backup_uuid VARCHAR(64) NOT NULL,
                component_type VARCHAR(32) NOT NULL,
                logical_name VARCHAR(191) NOT NULL,
                source_bucket VARCHAR(191) NULL,
                source_prefix VARCHAR(255) NULL,
                storage_key VARCHAR(255) NULL,
                manifest_key VARCHAR(255) NULL,
                object_count INT UNSIGNED NOT NULL DEFAULT 0,
                byte_size BIGINT UNSIGNED NOT NULL DEFAULT 0,
                content_sha256 CHAR(64) NULL,
                encrypted_sha256 CHAR(64) NULL,
                encryption_key_id VARCHAR(191) NULL,
                status VARCHAR(32) NOT NULL DEFAULT 'pending',
                error_message TEXT NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
                KEY idx_backup_components_backup (backup_uuid),
                KEY idx_backup_components_status (status),
                KEY idx_backup_components_type_name (component_type, logical_name)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
        );

        $db->query(
            "CREATE TABLE IF NOT EXISTS backup_jobs (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                job_type VARCHAR(32) NOT NULL,
                backup_uuid VARCHAR(64) NULL,
                status VARCHAR(32) NOT NULL DEFAULT 'queued',
                progress_percent TINYINT UNSIGNED NOT NULL DEFAULT 0,
                progress_message VARCHAR(255) NULL,
                payload_json LONGTEXT NULL,
                result_json LONGTEXT NULL,
                actor_user_id INT NULL,
                locked_at DATETIME NULL,
                lock_owner VARCHAR(191) NULL,
                started_at DATETIME NULL,
                completed_at DATETIME NULL,
                error_message TEXT NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
                KEY idx_backup_jobs_status_created (status, created_at),
                KEY idx_backup_jobs_backup (backup_uuid),
                KEY idx_backup_jobs_type_status (job_type, status)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
        );

        $db->query(
            "CREATE TABLE IF NOT EXISTS backup_restore_audit (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                restore_job_id BIGINT UNSIGNED NULL,
                preview_job_id BIGINT UNSIGNED NULL,
                backup_uuid VARCHAR(64) NOT NULL,
                actor_user_id INT NULL,
                target_environment VARCHAR(64) NOT NULL DEFAULT 'production',
                confirmation_fingerprint CHAR(64) NULL,
                reason TEXT NULL,
                ip_address VARCHAR(64) NULL,
                user_agent VARCHAR(255) NULL,
                pre_restore_backup_uuid VARCHAR(64) NULL,
                status VARCHAR(32) NOT NULL DEFAULT 'queued',
                started_at DATETIME NULL,
                completed_at DATETIME NULL,
                error_message TEXT NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
                KEY idx_backup_restore_audit_backup (backup_uuid),
                KEY idx_backup_restore_audit_job (restore_job_id),
                KEY idx_backup_restore_audit_created (created_at)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
        );

        self::$initialized = true;
    }
}
