<?php declare(strict_types = 1);

/**
 * @template-name Airtable Block Registration
 * @template-version 1.0.0
 * @template-description Registers a Airtable block for a given data source.
 * 
 * Template variables:
 * - DATA_SOURCE_UUID: The UUID of the data source to register the block for.
 * - BLOCK_REG_FN_SLUG: The slug of the data source to register the block for.
 * - TABLE_ID: The ID of the table to register the block for.
 * - TABLE_NAME: The name of the table to register the block for.
 * - AIRTABLE_OUTPUT_SCHEMA_MAPPINGS: The fields of the table to make available for the block.
 */

namespace RemoteDataBlocks\Snippets\Airtable;

use RemoteDataBlocks\Integrations\Airtable\AirtableDataSource;
use RemoteDataBlocks\WpdbStorage\DataSourceCrud;
use RemoteDataBlocks\Config\Query\HttpQuery;

function register_airtable__{{BLOCK_REG_FN_SLUG}}__block(): void {
	$data_source_config = DataSourceCrud::get_config_by_uuid( '{{DATA_SOURCE_UUID}}' );
	
	if ( is_wp_error( $data_source_config ) ) {
		return;
	}

	$data_source = AirtableDataSource::from_array( $data_source_config );
	$block_title = $data_source->get_display_name() . '/{{TABLE_NAME}}';

	$get_query = HttpQuery::from_array( [
		'data_source' => $data_source,
		'endpoint' => function ( array $input_variables ) use ( $data_source ): string {
			return $data_source->get_endpoint() . '/{{TABLE_ID}}/' . $input_variables['record_id'];
		},
		'input_schema' => [
			'record_id' => [
				'name' => 'Record ID',
				'type' => 'id',
			],
		],
		'output_schema' => [
			'is_collection' => false,
			'type' => {{AIRTABLE_OUTPUT_SCHEMA_MAPPINGS}},
		],
	] );

	$list_query = HttpQuery::from_array( [
		'data_source' => $data_source,
		'endpoint' => $data_source->get_endpoint() . '/{{TABLE_ID}}',
		'input_schema' => [],
		'output_schema' => [
			'is_collection' => true,
			'path' => '$.records[*]',
			'type' => {{AIRTABLE_OUTPUT_SCHEMA_MAPPINGS}},
		],
	] );

	register_remote_data_block( [
		'title' => $block_title,
		'render_query' => [
			'query' => $get_query,
		],
		'selection_queries' => [
			[
				'query' => $list_query,
				'type' => 'list',
			],
		],
	] );

	register_remote_data_block( [
		'title' => sprintf( '%s/%s Loop', $data_source->get_display_name(), '{{TABLE_NAME}}' ),
		'render_query' => [
			'query' => $list_query,
		],
	] );
}

add_action( 'init', __NAMESPACE__ . '\\register_airtable__{{BLOCK_REG_FN_SLUG}}__block' );
