import { placeBid as placeBidApi } from '../api/bid.js';
import {
    BID_FAILURE,
    BID_SUCCESS,
    PLACE_BID,
    SET_AUCTION_FILTER,
    SET_AUCTION_VIEW_MODE,
} from '../constants/actionTypes.js';
import { getActiveEventId } from '../selectors/activeEvent.js';
import { getAuthToken } from '../selectors/auth.js';

const placeBidFailure = (payload) => ({
    type: BID_FAILURE,
    payload,
});

const placeBidSuccess = (payload) => ({
    type: BID_SUCCESS,
    payload,
});

const handleBidFailure = (error) => (dispatch) => {
    console.error('[postBid]', error);
    dispatch(placeBidFailure(error));
};

const handleBidSuccess = (result) => (dispatch) => {
    dispatch(placeBidSuccess(result));
};

const startPlacingBid = (itemId) => ({
    type: PLACE_BID,
    payload: itemId,
});

export const changeFilterMode = (payload) => ({
    type: SET_AUCTION_FILTER,
    payload,
});

export const changeViewMode = (payload) => ({
    type: SET_AUCTION_VIEW_MODE,
    payload,
});

export const placeBid = ({ bidAmount, itemId, maxAmount }) => (dispatch, getState) => {
    const authToken = getAuthToken(getState());
    const eventId = getActiveEventId(getState());

    dispatch(startPlacingBid(itemId));
    placeBidApi({ bidAmount, eventId, itemId, maxAmount }, authToken)
        .then((payload) => dispatch(handleBidSuccess(payload)))
        .catch((err) => dispatch(handleBidFailure(err)));
};
