import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';
import getErrors from 'lib/getErrors';

import dnsApi from 'api/dns';

export default {
    removeRecord,
    submitRecord,
};

function removeRecord(domain, id) {
    return dnsApi.removeRecord(domain, id).then(response => {
        const errors = getErrors(response);

        if (!errors.isEmpty()) {
            return { errors };
        }

        dispatcher.dispatch(ActionTypes.DISCARD_DNS_RECORD, { id });
    });
}

function submitRecord(domain, recordData) {
    return dnsApi.submitRecord(domain, recordData).then(response => {
        const errors = getErrors(response);

        if (!errors.isEmpty()) {
            return { errors };
        }

        dispatcher.dispatch(ActionTypes.RECEIVE_DNS_RECORDS, response);
    });
}
