<?php

namespace App\Support;

final class AfterResponse
{
    private static bool $executing = false;

    /**
     * Run work after the HTTP response is sent (same process, no queue).
     * In console, or when already inside a deferred callback, runs immediately.
     */
    public static function run(callable $callback): void
    {
        if (self::$executing || app()->runningInConsole()) {
            $callback();

            return;
        }

        defer(function () use ($callback): void {
            self::$executing = true;
            try {
                $callback();
            } finally {
                self::$executing = false;
            }
        });
    }
}
