<?php

namespace Config;

use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\HotReloader\HotReloader;

/**
 * --------------------------------------------------------------------
 * Application Events
 * --------------------------------------------------------------------
 */
class EventsConfig
{
    /**
     * Register any application events.
     */
    public static function initialize(): void
    {
        // Biarkan kosong dulu.
        // Jangan panggil App\Events\Auth kalau file/class itu belum kamu buat.
    }
}

/*
 * --------------------------------------------------------------------
 * Pre-system
 * --------------------------------------------------------------------
 */
Events::on('pre_system', static function (): void {
    if (ENVIRONMENT !== 'testing') {
        if (ini_get('zlib.output_compression')) {
            throw FrameworkException::forEnabledZlibOutputCompression();
        }

        while (ob_get_level() > 0) {
            ob_end_flush();
        }

        ob_start(static fn ($buffer) => $buffer);
    }

    // Debug Toolbar
    if (CI_DEBUG && ! is_cli()) {
        Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
        service('toolbar')->respond();

        // Hot Reload
        if (ENVIRONMENT === 'development') {
            service('routes')->get('__hot-reload', static function (): void {
                (new HotReloader())->run();
            });
        }
    }
});
