<?php

namespace Miruni\RestApi;

use Miruni\Breakdance\Miruni_Breakdance_Service;
if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

use WP_Error;
use WP_REST_Response;


class Miruni_Breakdance_Global_Block_API extends Miruni_BaseAPI
{
    public static string $namespace = 'miruni/v1';
    public static string $route = '/breakdance-global-block/';

    public static function get_rest_url(): string
    {
        return self::_get_rest_url([]);
    }

    public static function setup(): void
    {
        // Register REST API endpoint
        add_action('rest_api_init', function () {
            register_rest_route(self::$namespace, self::$route, [
                'methods' => 'GET',
                'callback' => [__CLASS__, 'get_breakdance_global_block'],
                'permission_callback' => [__CLASS__, 'snippet_secret_required_permission_callback'],
                'args' => [
                    'global_block_id' => [
                        'required' => false,
                        'sanitize_callback' => 'absint',
                    ],
                ],
            ]);
        });
    }

    /**
     * Get block widgets data from options table
     * @param \WP_REST_Request<array<mixed>> $request
     * @return WP_Error|WP_REST_Response Response object or error
     */
    public static function get_breakdance_global_block(\WP_REST_Request $request): WP_Error|WP_REST_Response
    {
        $global_block_id = $request->get_param('global_block_id');
        if (empty($global_block_id)) {
            return new WP_Error('invalid_request', 'Global block ID is required', ['status' => 400]);
        }
        $block_data = Miruni_Breakdance_Service::get_global_block_data((int) $global_block_id);

        if (empty($block_data)) {
            return new WP_Error('not_found', 'Global block not found', ['status' => 404]);
        }

        $response_data = [
            'id' => $global_block_id,
            'content' => $block_data,
        ];


        // Return the structured widget data
        return new WP_REST_Response($response_data, 200);
    }
}
