import { Settings } from '@greenpay/models'

export interface RibbitBankTanResult {
	isTAN: boolean
	helpLink?: string
}

/**
 * Ask Green (via WordPress AJAX) whether a Ribbit-linked bank requires TAN verification.
 * Fail open to non-TAN when the endpoint is unavailable.
 */
export async function checkRibbitBankTan(
	bankId: number | string | undefined,
	institutionName: string,
	settings: Settings | null | undefined,
): Promise<RibbitBankTanResult> {
	const ajaxUrl = settings?.ribbitTanCheckAjaxUrl
	if (!ajaxUrl) {
		return { isTAN: false }
	}

	const formData = new FormData()
	formData.append('action', 'check_ribbit_bank_tan')
	formData.append('_ajax_nonce', settings.ribbitTanCheckNonce ?? '')
	if (bankId !== undefined && bankId !== null && String(bankId).trim() !== '') {
		formData.append('BankId', String(bankId))
	}
	if (institutionName.trim() !== '') {
		formData.append('InstitutionName', institutionName)
	}

	try {
		const response = await fetch(ajaxUrl, {
			method: 'POST',
			body: formData,
			credentials: 'same-origin',
		})
		const json = (await response.json()) as {
			success: boolean
			data?: { isTAN?: boolean; helpLink?: string }
		}

		if (!json.success || !json.data) {
			return { isTAN: false }
		}

		return {
			isTAN: json.data.isTAN === true,
			helpLink: json.data.helpLink || undefined,
		}
	} catch {
		return { isTAN: false }
	}
}
