/**
 * WordPress dependencies
 */
import apiFetch from '@safe-wordpress/api-fetch';
import { store as COMMANDS } from '@safe-wordpress/commands';
import { dispatch, select, resolveSelect } from '@safe-wordpress/data';
import { _x, sprintf } from '@safe-wordpress/i18n';

/**
 * External dependencies
 */
import { filter, keys, values } from 'lodash';
import { store as NAB_DATA } from '@nab/data';
import { store as NAB_EXPERIMENTS } from '@nab/experiments';
import { isExperimentTypeDisabled } from '@nab/utils';
import type { Experiment } from '@nab/types';

/**
 * Internal dependencies
 */
import DefaultIcon from '../../assets/src/images/icon.svg';

export async function registerCommands(): Promise< void > {
	const experimentTypes = select( NAB_EXPERIMENTS ).getExperimentTypes();
	if ( ! keys( experimentTypes ).length ) {
		return;
	}

	const allEntities = await resolveSelect( NAB_DATA ).getKindEntities();
	const postTypes = filter( allEntities, { kind: 'entity' } );
	const commandsDispatch = dispatch( COMMANDS );
	values( experimentTypes ).forEach( ( experimentType ) => {
		if ( isExperimentTypeDisabled( experimentType, postTypes ) ) {
			return;
		}

		const Icon = ( experimentType && experimentType.icon ) || DefaultIcon;
		void commandsDispatch.registerCommand( {
			name: `nelio-ab-testing/create-${ experimentType.name.replaceAll(
				'/',
				'-'
			) }-experiment`,
			label:
				experimentType.labels?.create ??
				sprintf(
					/* translators: %s = test type name */
					_x( 'Add new %s test', 'command', 'nelio-ab-testing' ),
					experimentType.title
				),
			icon: <Icon />,
			callback: ( { close } ) => {
				const addTestedPostScopeRule =
					'tested-post-with-consistency' ===
						experimentType?.supports?.scope ||
					'tested-product-with-consistency' ===
						experimentType?.supports?.scope;

				void apiFetch< Experiment >( {
					path: '/nab/v1/experiment',
					method: 'post',
					data: {
						type: experimentType.name,
						addTestedPostScopeRule,
					},
				} )
					.then( ( experiment ) => {
						window.location.href = experiment.links.edit;
					} )
					.catch( ( err: { message: string } ) => {
						// eslint-disable-next-line no-console
						console.error( err.message );
						close();
					} )
					.finally( () => close() );
			},
		} );
	} );
}
