<?php

namespace Miruni\RestApi;

use WP_Error;
use WP_REST_Response;

if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

class Miruni_Gutenberg_Blocks_API extends Miruni_BaseAPI
{
    public static string $namespace = 'miruni/v1';
    public static string $route = '/gutenberg-blocks/';

    public static function get_rest_url(int $page_id): string
    {
        $params = ['page_id' => $page_id];
        return self::_get_rest_url($params);
    }

    public static function setup(): void
    {
        add_action('rest_api_init', function () {
            register_rest_route(self::$namespace, self::$route, [
                'methods' => 'GET',
                'callback' => [__CLASS__, 'get_gutenberg_blocks'],
                'permission_callback' => [__CLASS__, 'snippet_secret_required_permission_callback'],
                'args' => [
                    'page_id' => [
                        'required' => true,
                        'validate_callback' => function ($param) {
                            return is_numeric($param);
                        },
                        'sanitize_callback' => 'absint',
                    ],
                ],
            ]);
        });
    }

    /**
     * Get parsed Gutenberg blocks for a given page/post.
     * @param \WP_REST_Request<array<mixed>> $request
     * @return WP_Error|WP_REST_Response
     */
    public static function get_gutenberg_blocks(\WP_REST_Request $request): WP_Error|WP_REST_Response
    {
        $post_id = $request->get_param('page_id');
        if (!is_integer($post_id)) {
            return new WP_Error('invalid_page_id', 'Invalid page ID provided.', ['status' => 400]);
        }
        $post = get_post((int) $post_id);

        if (!$post) {
            return new WP_Error('post_not_found', 'Post not found', ['status' => 404]);
        }


        if (!$post instanceof \WP_Post) {
            return new WP_Error('invalid_post', 'Invalid post object', ['status' => 500]);
        }

        $blocks = parse_blocks($post->post_content);

        $parsed_blocks = self::process_blocks($blocks);

        $response = [
            'post_id' => $post_id,
            'post_title' => $post->post_title,
            'blocks' => $parsed_blocks,
            'block_count' => count($parsed_blocks),
        ];

        return new WP_REST_Response($response, 200);
    }

    /**
     * Summary of process_blocks
     * @param array<mixed> $blocks
     * @return array<string,mixed>
     */
    private static function process_blocks(array $blocks): array
    {
        /**
         * @var array<string,mixed> $processed
         */
        $processed = [];
        foreach ($blocks as $index => $block) {

            if (!empty($block['blockName'])) {
                $block_data = [
                    'blockName' => $block['blockName'],
                    'attrs' => $block['attrs'] ?? [],
                    'innerHTML' => $block['innerHTML'] ?? '',
                    'innerContent' => $block['innerContent'] ?? [],
                ];

                // Process nested inner blocks recursively
                if (!empty($block['innerBlocks'])) {
                    $block_data['innerBlocks'] = self::process_blocks($block['innerBlocks']);
                }

                $processed[] = $block_data;
            }
        }

        return $processed;
    }
}
