<?php
/**
 * Models REST Controller
 *
 * Handles model listing and refresh operations.
 *
 * @package WP_Agentic_Writer
 */

/**
 * Class WP_Agentic_Writer_Controller_Models
 *
 * REST controller for model operations.
 *
 * @since 0.3.0
 */
class WP_Agentic_Writer_Controller_Models {

    /**
     * Sidebar instance for dependency access.
     *
     * @var WP_Agentic_Writer_Gutenberg_Sidebar
     */
    private $sidebar;

    /**
     * Constructor.
     *
     * @since 0.3.0
     * @param WP_Agentic_Writer_Gutenberg_Sidebar $sidebar Sidebar instance.
     */
    public function __construct( $sidebar ) {
        $this->sidebar = $sidebar;
    }

    /**
     * Handle get models request.
     *
     * @since 0.1.0
     * @return WP_REST_Response|WP_Error Response.
     */
    public function handle_get_models() {
        $provider = WP_Agentic_Writer_OpenRouter_Provider::get_instance();
        $models   = $provider->get_cached_models();

        if ( is_wp_error( $models ) ) {
            return $models;
        }

        return new WP_REST_Response( $models, 200 );
    }

    /**
     * Handle refresh models request.
     *
     * @since 0.1.0
     * @return WP_REST_Response|WP_Error Response.
     */
    public function handle_refresh_models() {
        $provider = WP_Agentic_Writer_OpenRouter_Provider::get_instance();
        $models   = $provider->fetch_and_cache_models( true );

        if ( is_wp_error( $models ) ) {
            return $models;
        }

        return new WP_REST_Response(
            [
                'models'  => $models,
                'message' => __(
                    'Models refreshed successfully.',
                    'wp-agentic-writer',
                ),
            ],
            200,
        );
    }
}
