<?php

namespace classes;

/**
 * Ensures additive schema for superuser invoice-period flags.
 */
class invoice_period_flag_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 invoice_period_flags (
                id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                source VARCHAR(32) NOT NULL,
                severity VARCHAR(32) NOT NULL,
                status VARCHAR(32) NOT NULL DEFAULT 'active',
                target_type VARCHAR(64) NOT NULL,
                target_id BIGINT NOT NULL,
                field VARCHAR(64) NULL,
                customer_number INT NULL,
                order_id BIGINT NULL,
                order_item_id BIGINT NULL,
                invoice_collection_id BIGINT NULL,
                xlvask_usage_log_id BIGINT NULL,
                definition_key VARCHAR(128) NULL,
                fingerprint VARCHAR(191) NULL,
                reason TEXT NULL,
                status_reason TEXT NULL,
                context_json JSON NULL,
                created_by INT NULL,
                status_changed_by INT NULL,
                status_changed_at DATETIME NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY uniq_invoice_period_flags_auto_fingerprint (source, fingerprint),
                KEY idx_invoice_period_flags_target (target_type, target_id, status),
                KEY idx_invoice_period_flags_customer_status (customer_number, status),
                KEY idx_invoice_period_flags_source_status (source, status),
                KEY idx_invoice_period_flags_order (order_id),
                KEY idx_invoice_period_flags_order_item (order_item_id),
                KEY idx_invoice_period_flags_invoice_collection (invoice_collection_id),
                KEY idx_invoice_period_flags_xlvask (xlvask_usage_log_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
        );

        products_schema_bootstrap::ensureTables();
        xlvask_usage_logs_schema_bootstrap::ensureTables();

        self::$initialized = true;
    }
}
