import { OrderItems, renderOrderItems } from '../order-items/renderOrderItems';
import { goToStep } from './goToStep';
import { showError } from '../form/showError';

export type OrderVerificationResponse = {
	success: boolean;
	data: {
		order_password?: string;
		order_items?: OrderItems
		error?: string;
	} };

export type VerifyOrder = (
	response: OrderVerificationResponse,
	step: number,
	form: JQuery<HTMLElement>,
) => void;

export const verifyOrder: VerifyOrder = ( response, step, form ) => {
	if ( response.success ) {
		if ( response.data && response.data.order_password && response.data.order_items ) {
			window.__wetail_shipping_return_portal.order_password = response.data.order_password;
			const returnStepElement = form
				.parents( '.wetail-return-portal__step' )
				.siblings( '.wetail-return-portal__step--items-return' );
			renderOrderItems( returnStepElement, response.data.order_items );
			goToStep( step + 1 );
		} else {
			console.error( '[WETAIL SHIPPING PORTAL] - order verification step error, order_password or order_items not exist ' );
			showError( form );
		}
	} else {
		let message;
		if ( response.data && response.data.error ) {
			message = response.data.error;
			console.error( '[WETAIL SHIPPING PORTAL] - order verification step error, response error: ', message );
		}

		showError( form, message );
	}
};
