from werkzeug.exceptions import BadRequest
from ..db.models import (Test, Action, ActionType, ItemDoesNotExistException,
                         ItemExistsException)
from .auth import auth
from .util import get_test


@auth()
def create(auth_user, body):
    try:
        test = Test.create(author=auth_user,
                           name=body.get('name'),
                           data=body.get('data'))
    except ItemDoesNotExistException as e:
        return dict(error=str(e), datum_id=e.item_id), 500
    except ItemExistsException as e:
        return dict(error=str(e), test_id=e.item_id), 500
    except Exception as e:
        err_msg = str(e)
        return dict(error=f'Could not add test: {err_msg}'), 500

    Action.create(ActionType.CREATE_TEST, auth_user, test)

    return test.to_obj(whos_asking=auth_user)


@auth()
@get_test()
def detail(test, auth_user):
    Action.create(ActionType.LIST_TEST, auth_user, test)
    return test.to_obj(whos_asking=auth_user)
