import requests

from .conftest import link, unlink


def test_up(conn):
    url = conn + '/up'
    resp = requests.get(url)
    resp.raise_for_status()
    res = resp.json()
    assert res['err'] == 0


def test_unlink(conn, update_data):
    resp = unlink(conn, update_data['name_id'])
    resp = unlink(conn, update_data['name_id'])
    res = resp.json()
    assert res['err'] == 'not-linked'


def test_link(conn, update_data):
    unlink(conn, update_data['name_id'])
    link(conn, update_data)
    link(conn, update_data)

    # wrong DUI number
    url = conn + '/link?NameID=%s' % update_data['name_id']
    payload = {
        'family_id': '999999',
        'firstname': update_data['family_payload']['rl1']['firstname'],
        'lastname': update_data['family_payload']['rl1']['lastname'],
        'dateBirth': update_data['family_payload']['rl1']['birth']['dateBirth'],
    }
    resp = requests.post(url, json=payload)
    resp.raise_for_status()
    res = resp.json()
    assert res == {
        'err': 'Family-readFamily-soap:Server',
        'err_class': 'passerelle.utils.jsonresponse.APIError',
        'err_desc': 'E02 : Le dossier numéro [999999] ne correspond à aucune famille',
        'data': None,
    }

    # wrong DUI firstname
    payload = {
        'family_id': update_data['family_id'],
        'firstname': 'plop',
        'lastname': update_data['family_payload']['rl1']['lastname'],
        'dateBirth': update_data['family_payload']['rl1']['birth']['dateBirth'],
    }
    resp = requests.post(url, json=payload)
    resp.raise_for_status()
    res = resp.json()
    assert res['err'] == 'not-found'
    assert 'RL1 does not match' in res['err_desc']
