/**
 * Form-field type to Brevo-attribute type compatibility.
 *
 * This exists because of one Brevo behaviour: when a value does not match
 * the attribute's declared type, the API accepts the request and silently
 * DROPS the value — no error, no warning, and the contact shows an empty
 * field. Every competing plugin inherits that failure. Flagging the
 * mismatch at mapping time is the fix.
 *
 * `ok` pairs travel as-is. `coerce` pairs are converted server-side by the
 * Coercer before they are sent. `risky` pairs are the ones that silently
 * vanish, and the editor marks them in red.
 */

import { __ } from '@wordpress/i18n';

const MATRIX = {
	text: {
		text: 'ok',
		category: 'coerce',
		'multiple-choice': 'coerce',
		float: 'risky',
		date: 'risky',
		boolean: 'risky',
	},
	email: { text: 'ok', float: 'risky', date: 'risky', boolean: 'risky' },
	textarea: { text: 'ok', float: 'risky', date: 'risky', boolean: 'risky' },
	name: { text: 'ok', float: 'risky', date: 'risky', boolean: 'risky' },
	address: { text: 'ok', float: 'risky', date: 'risky', boolean: 'risky' },
	number: {
		float: 'ok',
		text: 'coerce',
		id: 'coerce',
		date: 'risky',
		boolean: 'risky',
	},
	date: { date: 'ok', text: 'coerce', float: 'risky', boolean: 'risky' },
	phone: { text: 'ok', float: 'risky', date: 'risky', boolean: 'risky' },
	checkbox: { boolean: 'ok', text: 'coerce', float: 'coerce', date: 'risky' },
	select: {
		text: 'ok',
		category: 'coerce',
		'multiple-choice': 'coerce',
		float: 'coerce',
		date: 'risky',
		boolean: 'coerce',
	},
	multiselect: {
		'multiple-choice': 'ok',
		text: 'coerce',
		category: 'coerce',
		float: 'risky',
		date: 'risky',
		boolean: 'risky',
	},
	file: { text: 'ok', float: 'risky', date: 'risky', boolean: 'risky' },
};

/**
 * Describe how a form field and a Brevo attribute fit together.
 *
 * @param {string} fieldType     Our normalised form-field type.
 * @param {string} attributeType Brevo attribute type.
 * @return {{level: string, message: string}} Hint for the editor row.
 */
export function compatibility( fieldType, attributeType ) {
	if ( ! fieldType || ! attributeType ) {
		return {
			level: 'muted',
			message: __( '—', 'rewind-form-bridge-for-brevo' ),
		};
	}

	const verdict = MATRIX[ fieldType ]?.[ attributeType ];

	if ( verdict === 'ok' ) {
		return {
			level: 'ok',
			message: __( 'Types match', 'rewind-form-bridge-for-brevo' ),
		};
	}

	if ( verdict === 'coerce' ) {
		return {
			level: 'warn',
			message: __( 'Converted on send', 'rewind-form-bridge-for-brevo' ),
		};
	}

	if ( verdict === 'risky' ) {
		return {
			level: 'risky',
			message: __(
				'Brevo will drop this value',
				'rewind-form-bridge-for-brevo'
			),
		};
	}

	return {
		level: 'warn',
		message: __( 'Unverified pairing', 'rewind-form-bridge-for-brevo' ),
	};
}
