/**
 * REST API helpers built on @wordpress/api-fetch.
 */
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';

const TOURS_BASE = '/wp/v2/vist360-tours';

export const config = window.vist360Admin || {
	maxScenes: 7,
	canManage: false,
	sceneTypes: [ 'sphere', 'cube', 'flat', 'little_planet', 'cylinder' ],
	templates: [],
	lockedTemplates: [],
	viewerDefaults: {},
};

export const fetchTours = ( query = {} ) =>
	apiFetch( {
		path: addQueryArgs( TOURS_BASE, {
			context: 'edit',
			_embed: 'wp:featuredmedia',
			per_page: 50,
			status: 'publish,draft,private,pending,future',
			...query,
		} ),
	} );

export const fetchTour = ( id ) =>
	apiFetch( {
		path: addQueryArgs( `${ TOURS_BASE }/${ id }`, { context: 'edit' } ),
	} );

export const saveTour = ( id, data ) =>
	apiFetch( {
		path: id ? `${ TOURS_BASE }/${ id }` : TOURS_BASE,
		method: 'POST',
		data,
	} );

export const deleteTour = ( id ) =>
	apiFetch( {
		path: `${ TOURS_BASE }/${ id }`,
		method: 'DELETE',
		data: { force: true },
	} );

export const fetchAnalytics = ( query = {} ) =>
	apiFetch( { path: addQueryArgs( '/vist360/v1/analytics', query ) } );

export const exportTour = ( id ) =>
	apiFetch( { path: `/vist360/v1/tours/${ id }/export` } );

export const importTour = ( data ) =>
	apiFetch( { path: '/vist360/v1/tours/import', method: 'POST', data } );

export const fetchSettings = () =>
	apiFetch( { path: '/wp/v2/settings' } ).then(
		( settings ) => settings.vist360_settings || {}
	);

export const saveSettings = ( values ) =>
	apiFetch( {
		path: '/wp/v2/settings',
		method: 'POST',
		data: { vist360_settings: values },
	} ).then( ( settings ) => settings.vist360_settings || {} );

/**
 * Open the WordPress media library and resolve with the chosen attachment.
 *
 * @param {string} title Frame title.
 * @return {Promise<Object>} Selected attachment.
 */
export const pickImage = ( title ) =>
	new Promise( ( resolve ) => {
		const frame = window.wp.media( {
			title,
			multiple: false,
			library: { type: 'image' },
		} );
		frame.on( 'select', () => {
			resolve( frame.state().get( 'selection' ).first().toJSON() );
		} );
		frame.open();
	} );

/**
 * Resolve scene image URLs for the live preview.
 *
 * @param {Array} scenes Scenes with image_id/image_url.
 * @return {Array} Scenes ready for the viewer.
 */
export const scenesForViewer = ( scenes ) =>
	scenes
		.filter( ( scene ) => scene.image_url )
		.map( ( scene ) => ( { ...scene, thumb_url: scene.image_url } ) );
