import re

from app_new.extensions import db


def test_api_key_is_hashed_and_authenticates(authenticated_client, app):
    response = authenticated_client.post('/admin/settings/api-key')
    assert response.status_code == 200
    match = re.search(rb'value="(gmao_[^"]+)"', response.data)
    assert match
    raw_key = match.group(1).decode()

    from app_new.core.models.settings import AppSettings
    with app.app_context():
        stored = AppSettings.get('api_key_hash')
        assert stored
        assert raw_key not in stored

    anonymous = app.test_client()
    assert anonymous.get('/api/v1/status', headers={'X-API-Key': raw_key}).status_code == 200
    assert anonymous.get('/api/v1/status', headers={'X-API-Key': 'incorrecte'}).status_code == 401


def test_api_pagination_is_bounded(authenticated_client):
    response = authenticated_client.get('/api/v1/equipments?page=-4&per_page=10000')
    assert response.status_code == 200
    assert response.get_json()['page'] == 1
    assert response.get_json()['per_page'] == 100


def test_document_permissions_follow_parent_domain(app):
    from app_new.core.authorization import required_permission
    with app.test_request_context('/'):
        assert required_permission('documents.download_intervention_document', 'GET') == 'intervention.view'
        assert required_permission('documents.delete_intervention_document', 'POST') == 'intervention.manage'
        assert required_permission('documents.download_equipment_document', 'GET') == 'patrimoine.view'
        assert required_permission('documents.upload_equipment', 'POST') == 'patrimoine.manage'
