import json

import jsonschema
import pytest

from inventory_provider.tasks import worker

DEFAULT_REQUEST_HEADERS = {
    "Content-type": "application/json",
    "Accept": ["application/json"]
}


INTERFACE_LIST_SCHEMA = {
    '$schema': 'http://json-schema.org/draft-07/schema#',

    'definitions': {
        'ifc-info': {
            'type': 'object',
            'properties': {
                'description': {'type': 'string'},
                'router': {'type': 'string'},
                'interface': {'type': 'string'},
                'user': {'type': 'string'}
            },
            'required': ['router', 'interface', 'description'],
            'additionalProperties': False
        },
    },

    'type': 'array',
    'items': {'$ref': '#/definitions/ifc-info'}
}


@pytest.mark.parametrize('category', ['mdvpn', 'lhcone', 'MDVpn', 'LHCONE'])
def test_service_category(client, mocked_worker_module, category):
    worker._build_service_category_interface_list()
    rv = client.get(
        f'/poller/services/{category}',
        headers=DEFAULT_REQUEST_HEADERS)
    assert rv.status_code == 200
    assert rv.is_json
    response_data = json.loads(rv.data.decode('utf-8'))
    jsonschema.validate(response_data, INTERFACE_LIST_SCHEMA)
    assert response_data, 'expected a non-empty list'


@pytest.mark.parametrize('category', ['mdvpn ', ' mdvpn', 'mdvpn1', 'aaa'])
def test_service_category_not_found(client, mocked_worker_module, category):
    worker._build_service_category_interface_list()
    rv = client.get(
        f'/poller/services/{category}',
        headers=DEFAULT_REQUEST_HEADERS)
    assert rv.status_code == 404