# authentic2 - versatile identity manager
# Copyright (C) 2010-2019 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/>.


import faker
import pytest
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType

from authentic2.models import Attribute, AttributeValue

User = get_user_model()

pytestmark = pytest.mark.slow


@pytest.fixture
def large_userbase(db, freezer):
    dob_attribute = Attribute.objects.create(
        kind='birthdate', name='birthdate', label='birthdate', required=True
    )

    # fix time window
    freezer.move_to('2020-01-01')
    fake = faker.Faker(locale='fr_FR')
    faker.Faker.seed(0)

    for i in range(100):
        User.objects.bulk_create(
            User(
                first_name=fake.first_name() + ' ' + fake.first_name(),
                last_name=fake.last_name(),
                email=fake.ascii_safe_email(),
            )
            for i in range(1000)
        )

    user_ids = User.objects.values_list('id', flat=True)
    user_ct = ContentType.objects.get_for_model(User)

    AttributeValue.objects.bulk_create(
        AttributeValue(
            content_type=user_ct,
            object_id=user_id,
            attribute=dob_attribute,
            verified=True,
            multiple=False,
            content=fake.date(),
        )
        for user_id in user_ids
    )


def test_large_userbase_find_duplicates(large_userbase, app, admin):
    app.authorization = ('Basic', (admin.username, admin.username))

    user = User.objects.first()
    params = {
        'first_name': user.first_name,
        'last_name': user.last_name,
    }

    for i in range(100):
        resp = app.get('/api/users/find_duplicates/', params=params)
        assert len(resp.json['data']) >= 1


def test_large_userbase_find_duplicates_with_birthdate(large_userbase, app, admin):
    app.authorization = ('Basic', (admin.username, admin.username))

    user = User.objects.first()
    params = {
        'first_name': user.first_name,
        'last_name': user.last_name,
        'birthdate': str(user.attributes.birthdate),
    }

    for i in range(100):
        resp = app.get('/api/users/find_duplicates/', params=params)
        assert len(resp.json['data']) >= 1
