import apiFetch from '@wordpress/api-fetch';

const getConnectionStatus = ( { connected, settings } ) => {
	if ( connected ) {
		return 'ok';
	}
	const empty = checkIfEmpty( settings );
	if ( empty ) {
		return 'empty';
	}
	return 'error';
};

const checkIfEmpty = ( settings ) => {
	if ( ! settings ) {
		return true;
	}
	if ( typeof settings === 'string' ) {
		return ! settings;
	}
	// Loop through all settings keys and any has value all are empty, return true
	return Object.values( settings ).every( ( value ) => ! value );
};

const handleMigration = async ( endpoint ) => {
	const response = await apiFetch( {
		url: `${ endpoint }`,
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
	} );
	return response;
};

const nextAutomationFormStep = ( {
	connected,
	prevStep,
	settings,
}: {
	connected: boolean;
	prevStep?: number;
	settings: any;
} ) => {
	const isEmpty = checkIfEmpty( settings );
	if ( ! connected || isEmpty ) {
		return 1;
	}
	const defaultChannel = settings.channel.id;
	if ( ! defaultChannel || prevStep === 1 ) {
		return 2;
	}
	if ( prevStep === 2 ) {
		return 3;
	}
	return 0;
};

const makeOptionsOfChannels = (
	channels: Array< { id: string; name: string } >,
	first: { value: string; label: string }
) => {
	const options = channels.map( ( channel ) => ( {
		value: channel.id,
		label: channel.name,
	} ) );
	options.sort( ( a, b ) => ( a.value > b.value ? 1 : -1 ) );
	options.unshift( first );
	return options;
};

export {
	checkIfEmpty,
	getConnectionStatus,
	handleMigration,
	makeOptionsOfChannels,
	nextAutomationFormStep,
};
