import { RibbitSessionBilling } from './getCheckoutBillingDetails'

export const RIBBIT_BILLING_FIELD_LABELS: Record<keyof RibbitSessionBilling, string> = {
	first_name: 'first name',
	last_name: 'last name',
	email: 'email address',
	phone: 'phone number',
	address_1: 'billing address',
	address_2: 'billing address line 2',
	city: 'city',
	state: 'state',
	postcode: 'ZIP code',
	country: 'country',
}

const REQUIRED_FIELDS = [
	'first_name',
	'last_name',
	'email',
	'phone',
	'address_1',
	'city',
	'state',
	'postcode',
] as const satisfies (keyof RibbitSessionBilling)[]

const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

export interface RibbitSessionBillingValidation {
	valid: boolean
	message: string
	missingFields: (keyof RibbitSessionBilling)[]
}

const formatMissingFieldMessage = (fields: (keyof RibbitSessionBilling)[]): string => {
	const labels = fields.map((field) => RIBBIT_BILLING_FIELD_LABELS[field])

	if (labels.length === 1) {
		return `Please enter your ${labels[0]} before using Bank Login.`
	}

	const last = labels.pop()
	return `Please enter your ${labels.join(', ')} and ${last} before using Bank Login.`
}

export const validateRibbitSessionBilling = (
	billing: RibbitSessionBilling,
): RibbitSessionBillingValidation => {
	const missingFields = REQUIRED_FIELDS.filter((field) => !billing[field])

	if (missingFields.length > 0) {
		return {
			valid: false,
			message: formatMissingFieldMessage([...missingFields]),
			missingFields: [...missingFields],
		}
	}

	if (!EMAIL_PATTERN.test(billing.email)) {
		return {
			valid: false,
			message: 'Please enter a valid email address before using Bank Login.',
			missingFields: ['email'],
		}
	}

	return {
		valid: true,
		message: '',
		missingFields: [],
	}
}
