import PlaidComponent from '../../components/Plaid/Plaid'
import { Plaid } from '@greenpay/models'
import { BankLoginCheckoutContext, BankLoginClassicPayloadContext, IBankLoginProvider } from './types'

export const plaidBankLoginProvider: IBankLoginProvider = {
	id: 'plaid',
	Component: PlaidComponent,
	resolveState(ctx: BankLoginCheckoutContext): Plaid | null {
		const plaidState = ctx.getPlaid()
		const fallbackToken = ctx.getHiddenInputValue('wc_greenpay_token')
		const fallbackInstitution = ctx.getHiddenInputValue('wc_greenpay_institution')

		return (
			plaidState ??
			(fallbackToken && fallbackInstitution
				? {
						token: fallbackToken,
						institution: fallbackInstitution,
						isTAN: false,
						success: true,
						mask: '',
					}
				: null)
		)
	},
	validate(ctx: BankLoginCheckoutContext): boolean {
		return ctx.validatePlaid(this.resolveState(ctx))
	},
	buildPaymentMethodData(ctx: BankLoginCheckoutContext) {
		const plaid = this.resolveState(ctx)
		return {
			payment_method: this.id,
			token: plaid?.token,
			institution: plaid?.institution,
		}
	},
	syncClassicPayload(ctx: BankLoginClassicPayloadContext) {
		const plaid = this.resolveState(ctx)
		ctx.setValue('wc_greenpay_token', plaid?.token ?? '')
		ctx.setValue('wc_greenpay_institution', plaid?.institution ?? '')
	},
	clearClassicPayload(ctx: BankLoginClassicPayloadContext) {
		ctx.setValue('wc_greenpay_token', '')
		ctx.setValue('wc_greenpay_institution', '')
	},
}
