import { call, put } from 'redux-saga/effects';
import * as types from '~/store/actionTypes';
import { API } from '~/lib/sdk';

export function* getVerification(action) {
	try {
		const response = yield call(API.auth.getVerification, { payload: action.payload });
		yield put({ type: types.REQUEST_VERIFICATION_SUCCESS, payload: response });
		yield call(action.payload.resolve, response);
	} catch (error) {
		yield put({ type: types.REQUEST_VERIFICATION_ERROR, payload: { error } });
		yield call(action.payload.reject, action, error);
	}
}

export function* verifyCode(action) {
	try {
		const response = yield call(API.auth.verifyCode, { payload: action.payload });
		yield put({ type: types.VERIFY_CODE_SUCCESS, payload: response });
		yield call(action.payload.resolve, response);
	} catch (error) {
		yield put({ type: types.VERIFY_CODE_ERROR, payload: { error } });
		yield call(action.payload.reject, action, error);
	}
}

export function* login(action) {
	try {
		const response = yield call(API.auth.login, { payload: action.payload });
		yield put({ type: types.REQUEST_LOGIN_SUCCESS, payload: response });
		yield call(action.payload.resolve, response);
	} catch (error) {
		yield put({ type: types.REQUEST_LOGIN_ERROR, payload: { error } });
		yield call(action.payload.reject, action, error);
	}
}

export function* registerBeneficiary(action) {
	try {
		const response = yield call(API.auth.registerBeneficiary, { payload: action.payload });
		yield put({ type: types.REGISTER_BENEFICIARY_SUCCESS, payload: response });
		yield call(action.payload.resolve, response);
	} catch (error) {
		yield put({ type: types.REGISTER_BENEFICIARY_ERROR, payload: { error } });
		yield call(action.payload.reject, action, error);
	}
}
