<?php
/**
 * Template tags for theme developers.
 *
 * @package DataStream
 */

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

if ( ! function_exists( 'datastream_get_records' ) ) {
	/**
	 * Retrieve ingested records with decoded payloads.
	 *
	 * @param array<string, mixed> $args {
	 *     @type string $stream Stream type filter ('' = all).
	 *     @type int    $limit  Max records (1–100, default 10).
	 * }
	 * @return array<int, array<string, mixed>> Each record has external_id,
	 *                                          stream_type, source, updated_at,
	 *                                          and `data` (decoded payload).
	 */
	function datastream_get_records( $args = array() ) {
		return DataStream_Renderer::get_records( $args );
	}
}

if ( ! function_exists( 'datastream_get_record' ) ) {
	/**
	 * Retrieve a single record's decoded payload by external ID (cached).
	 *
	 * @param string $external_id The record's external identifier.
	 * @return array<string, mixed>|null
	 */
	function datastream_get_record( $external_id ) {
		return DataStream_Provider::get_data( $external_id );
	}
}

if ( ! function_exists( 'datastream_get_field' ) ) {
	/**
	 * Retrieve one field (dot paths allowed) from a record's payload.
	 *
	 * @param string $external_id Record identifier.
	 * @param string $field       Field name or dot path, matched verbatim.
	 * @param mixed  $default     Returned when the record or field is missing.
	 * @return mixed
	 */
	function datastream_get_field( $external_id, $field, $default = null ) {
		$data = DataStream_Provider::get_data( $external_id );

		if ( null === $data ) {
			return $default;
		}

		$value = DataStream_Renderer::pluck( $data, $field );

		return null === $value ? $default : $value;
	}
}

if ( ! function_exists( 'datastream_render_list' ) ) {
	/**
	 * Render records as HTML using a bundled template.
	 *
	 * @param array<string, mixed> $args See DataStream_Renderer::render_list().
	 * @return string HTML (already escaped).
	 */
	function datastream_render_list( $args = array() ) {
		return DataStream_Renderer::render_list( $args );
	}
}
