import { PR_CHANGE_REVIEWER_STATE } from 'bitbucket/internal/bbui/actions/pull-request';
import pullRequestReviewers from 'bitbucket/internal/bbui/reducers/pull-request-reviewers';

QUnit.module('pull-request-reviewers');

const reviewers = [{
    state: 'UNAPPROVED',
    user: {
        name: 'foo',
    },
}, {
    state: 'UNAPPROVED',
    user: {
        name: 'bar',
    },
}];

QUnit.test('it applies an optimistic change', function(assert) {
    const newState = pullRequestReviewers(reviewers, {
        type: PR_CHANGE_REVIEWER_STATE,
        payload: {
            newState: 'NEEDS_WORK',
            user: {
                name: 'bar',
            },
        },
        meta: {
            isPending: true,
        },
    });
    assert.deepEqual(newState, [{
        state: 'UNAPPROVED',
        user: {
            name: 'foo',
        },
    }, {
        state: 'NEEDS_WORK',
        user: {
            name: 'bar',
        },
    }]);
});

QUnit.test('it rolls back on failure', function(assert) {
    const newState = pullRequestReviewers(reviewers, {
        type: PR_CHANGE_REVIEWER_STATE,
        payload: {
            error: {
                status: 401,
                statusText: 'Unauthorized',
            },
        },
        meta: {
            isPending: false,
        },
    });
    assert.deepEqual(newState, [{
        state: 'UNAPPROVED',
        user: {
            name: 'foo',
        },
    }, {
        state: 'UNAPPROVED',
        user: {
            name: 'bar',
        },
    }]);
});

QUnit.test('it rolls back if there is no payload', function(assert) {
    const newState = pullRequestReviewers(reviewers, {
        type: PR_CHANGE_REVIEWER_STATE,
        meta: {
            isPending: false,
        },
    });
    assert.deepEqual(newState, [{
        state: 'UNAPPROVED',
        user: {
            name: 'foo',
        },
    }, {
        state: 'UNAPPROVED',
        user: {
            name: 'bar',
        },
    }]);
});
