/**
 * Build conditional-tag syntax from row state.
 *
 * @package EDD\Pro\Emails\ConditionalTags
 */

/**
 * Check whether a condition is boolean (no operator/value needed).
 *
 * @param {string}   conditionKey The condition key.
 * @param {Object[]} conditions   Available condition metadata.
 * @return {boolean}
 */
function isBooleanCondition( conditionKey, conditions ) {
	const condition = conditions.find( function ( c ) {
		return c.key === conditionKey;
	} );

	return !! condition && condition.operators.length === 0;
}

/**
 * Check whether a row is complete enough to include in the expression.
 *
 * @param {Object}   row        Row state.
 * @param {Object[]} conditions Available condition metadata.
 * @return {boolean}
 */
export function isRowComplete( row, conditions ) {
	if ( ! row.conditionKey ) {
		return false;
	}

	if ( isBooleanCondition( row.conditionKey, conditions ) ) {
		return true;
	}

	return !! row.operator && String( row.value ?? '' ).trim() !== '';
}

/**
 * Builds an expression string from complete builder rows.
 *
 * @param {Array}    rows       Builder rows.
 * @param {Object[]} conditions Available condition metadata.
 * @return {string} Expression string for `{if ...}`.
 */
function buildExpression( rows, conditions ) {
	const completeRows = rows.filter( function ( row ) {
		return isRowComplete( row, conditions );
	} );

	return completeRows
		.map( function ( row, index ) {
			let condition;

			if ( isBooleanCondition( row.conditionKey, conditions ) ) {
				condition = row.conditionKey;
			} else {
				const escapedValue = String( row.value ).trim().replaceAll( '"', '\\"' );
				condition = row.conditionKey + row.operator + '"' + escapedValue + '"';
			}

			if ( 0 === index ) {
				return condition;
			}

			const conjunction = row.conjunction === 'OR' ? 'OR' : 'AND';
			return conjunction + ' ' + condition;
		} )
		.join( ' ' );
}

/**
 * Builds the final conditional tag block.
 *
 * @param {Array}    rows       Builder rows.
 * @param {string}   content    Inner content to wrap.
 * @param {Object[]} conditions Available condition metadata.
 * @return {string} Conditional tag syntax.
 */
export function buildConditionalSyntax( rows, content, conditions ) {
	const expression = buildExpression( rows, conditions );
	const body = String( content || '' );

	return '{if ' + expression + '}' + body + '{/if}';
}
