# authentic2 - versatile identity manager
# Copyright (C) 2010-2021 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from authentic2.custom_user.models import User
from authentic2_idp_oidc.models import OIDCClient
from authentic2_idp_oidc.utils import make_sub


def test_api_synchronization(app, oidc_client):
    oidc_client.has_api_access = True
    oidc_client.save()
    users = [User.objects.create(username='user-%s' % i) for i in range(10)]
    for user in users[5:]:
        user.delete()
    deleted_subs = {make_sub(oidc_client, user) for user in users[5:]}

    app.authorization = ('Basic', (oidc_client.client_id, oidc_client.client_secret))
    status = 200
    if oidc_client.identifier_policy not in (OIDCClient.POLICY_PAIRWISE_REVERSIBLE, OIDCClient.POLICY_UUID):
        status = 401
    response = app.post_json(
        '/api/users/synchronization/',
        params={'known_uuids': [make_sub(oidc_client, user) for user in users]},
        status=status,
    )
    if status == 200:
        assert response.json['result'] == 1
        assert set(response.json['unknown_uuids']) == deleted_subs
