import { call, put } from 'redux-saga/effects';
import { get } from 'services/requests';
import { Api } from 'routes/Api';
import { handleError } from 'modules/error-handler';
import * as actions from 'lib/redux/actions/users-actions';


export function* fetchUser(action): Generator {
	try {
		const res: Record<string, any> = yield call(() => get({
			url: Api.users + '/' + action.username
		}));

		yield put(actions.fetchedUser({ data: res.data }));

	}
	catch (error) {
		yield put(actions.failedFetchUser({ error: error.message }));

		handleError(error);
	}
}



export function* fetchMyAds(): Generator {
	try {
		const res: Record<string, any> = yield call(() => get({
			url: Api.users + '/my-ads'
		}));

		yield put(actions.fetchedMyAds({ data: res.data }));
	}
	catch (error) {
		yield put(actions.failedFetchMyAds({ error: error.message }));

		handleError(error);
	}
}



export function* fetchMyShops(): Generator {
	try {
		const res: Record<string, any> = yield call(() => get({
			url: Api.users + '/my-shops'
		}));

		yield put(actions.fetchedMyShops({ data: res.data }));
	}
	catch (error) {
		yield put(actions.failedFetchMyShops({ error: error.message }));

		handleError(error);
	}
}



export function* fetchMyFavorites(): Generator {
	try {
		const res: Record<string, any> = yield call(() => get({
			url: Api.users + '/my-favorites'
		}));

		yield put(actions.fetchedMyFavorites({ data: res.data }));
	}
	catch (error) {
		yield put(actions.failedFetchMyFavorites({ error: error.message }));

		handleError(error);
	}
}



