<?php

namespace Formatrica\REST;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Edition REST-controller registry (Phase 6, plan §6.8).
 *
 * The Free Rest_Service_Provider is statically Free-only — it neither names
 * nor conditionally instantiates Pro controllers. The Pro service provider
 * adds factories here; they are resolved lazily at rest_api_init time, so
 * provider registration order can never drop a controller.
 */
final class Rest_Controller_Registry
{
    /** @var array<int, callable():Rest_Controller> */
    private static array $factories = [];

    /** @var array<int, Rest_Controller>|null */
    private static ?array $resolved = null;

    /**
     * @param callable():Rest_Controller $factory
     */
    public static function add(callable $factory): void
    {
        self::$factories[] = $factory;
        self::$resolved = null;
    }

    /**
     * @return array<int, Rest_Controller>
     */
    public static function controllers(): array
    {
        if (self::$resolved === null) {
            self::$resolved = [];
            foreach (self::$factories as $factory) {
                $controller = $factory();
                if ($controller instanceof Rest_Controller) {
                    self::$resolved[] = $controller;
                }
            }
        }

        return self::$resolved;
    }
}
