import { List } from 'immutable';

import { fetchAuctionStatus as fetchActionStatusApi } from '../api/actionStatus.js';
import { AUCTIONS_UPDATED } from '../constants/actionTypes.js';
import { getActiveEventId } from '../selectors/activeEvent.js';
import { getAuthToken } from '../selectors/auth.js';

import Auction from '../domain/Auction.js';

const auctionsUpdated = (payload) => ({
    type: AUCTIONS_UPDATED,
    payload,
});

const autionStatusLoadSuccess = (auctions) => (dispatch) => {
    const payload = List(auctions).map((i) => Auction.fromJS(i));
    dispatch(auctionsUpdated(payload));
};

export const fetchAuctionStatus = () => (dispatch, getState) => {
    const authToken = getAuthToken(getState());
    const eventId = getActiveEventId(getState());

    return fetchActionStatusApi(eventId, authToken)
        .then((payload) => dispatch(autionStatusLoadSuccess(payload)))
        .catch((err) => console.error('[actions::getStatus]', err));
};
