import { call, put } from 'redux-saga/effects';
import { get } from 'services/requests';
import { get as get2 } from 'services/requests-v2';
import { Api } from 'routes/Api';
import api from 'routes/api-v2';
import { handleError } from 'modules/error-handler';
import * as actions from 'lib/redux/actions/news-actions';


export function* fetchSingleNews(action): Generator {
	try {
		const res: Record<string, any> = yield call(() => get2({
			url: api('news.show', {slug: action.data.slug}, action.options)
		}));

		yield put(actions.fetchedSingleNews({ data: res.data }));

	}
	catch (error) {
		yield put(actions.failedFetchSingleNews({ error: error.message }));

		handleError(error);
	}
}

export function* fetchMultipleNews(action): Generator {
	try {
		const res : any = yield call(() =>
			get2({
				url: api('news.index', null, action.options),
			}),
		);

		yield put(actions.fetchedMultipleNews({ data: res.data,
			pagination: res.pagination,
		}));
	}
	catch (error) {
		yield put(actions.failedFetchMultipleNews({ error: error.message }));

		handleError(error);
	}
}




export function* fetchNewsCategories() {
	try {
		const res = yield call(() => get({
			url: Api.news_categories
		}));

		yield put(actions.fetchedNewsCategories({ data: res.data }));
	}
	catch (error) {
		yield put(actions.failedFetchNewsCategories({ error }));
	}
}
