/**
 * Hook for fetching query templates from the REST API.
 *
 * @package RawTypeOE
 */

import { useState, useEffect } from '@wordpress/element';
import apiFetch from '../utils/apiFetch';

const templatesCache = new Map();

/**
 * Fetch templates from the REST API, optionally filtered by entity.
 *
 * @param {string|null} entity Entity to filter by (orders, products, customers) or null for all.
 * @return {Object} { templates, isLoading, error }
 */
export function useTemplates( entity ) {
	const cacheKey = entity || '__all__';
	const cached = templatesCache.has( cacheKey ) ? templatesCache.get( cacheKey ) : null;

	const [ templates, setTemplates ] = useState( cached || [] );
	const [ isLoading, setIsLoading ] = useState( ! cached );
	const [ error, setError ] = useState( null );

	useEffect( () => {
		if ( templatesCache.has( cacheKey ) ) {
			setTemplates( templatesCache.get( cacheKey ) );
			setIsLoading( false );
			return;
		}

		const controller = new AbortController();

		setIsLoading( true );
		setError( null );

		let path = '/rawtype_oe/v1/templates';
		if ( entity ) {
			path += '?entity=' + encodeURIComponent( entity );
		}

		apiFetch( { path, signal: controller.signal } )
			.then( ( data ) => {
				templatesCache.set( cacheKey, data );
				setTemplates( data );
				setIsLoading( false );
			} )
			.catch( ( err ) => {
				if ( 'AbortError' !== err.name ) {
					setError( err );
					setIsLoading( false );
				}
			} );

		return () => controller.abort();
	}, [ entity, cacheKey ] );

	return { templates, isLoading, error };
}

export default useTemplates;
