import pytest

from credmgr.exceptions import Conflict, NotFound, ServerError
from credmgr.models import SentryToken


def test_create_sentry_token(recorder, credential_manager):
    data = {"name": "test_sentry_token", "dsn": "https://key@sentry.jesassn.org/id"}
    sentry_token = credential_manager.sentry_token.create(**data)
    for key, value in data.items():
        assert getattr(sentry_token, key) == value


def test_create_sentry_token_other_user(recorder, credential_manager):
    data = {
        "name": "test_sentry_token",
        "dsn": "https://key@sentry.jesassn.org/id",
        "owner": 4,
    }
    sentry_token = credential_manager.sentry_token.create(**data)
    for key, value in data.items():
        if key == "owner":
            assert getattr(sentry_token, key).id == value
            continue
        assert getattr(sentry_token, key) == value


def test_create_sentry_token_bad_params(recorder, credential_manager):
    data = {"name": "se", "dsn": "https://key@sentry.jesassn.org/id2"}
    with pytest.raises(ServerError):
        _ = credential_manager.sentry_token.create(**data)


def test_create_sentry_token_existing(recorder, credential_manager):
    data = {"name": "sentry_token", "dsn": "https://key@sentry.jesassn.org/id"}
    with pytest.raises(Conflict):
        _ = credential_manager.sentry_token.create(**data)


def test_delete_sentry_token(recorder, credential_manager):
    sentry_token = credential_manager.sentry_token(1)
    sentry_token.delete()
    with pytest.raises(NotFound):
        _ = credential_manager.sentry_token(1)


def test_edit_sentry_token(recorder, credential_manager):
    sentry_token = credential_manager.sentry_token(2)
    sentry_token.edit(dsn="https://key@sentry.jesassn.org/id_new")
    assert sentry_token.dsn == "https://key@sentry.jesassn.org/id_new"


def test_edit_sentry_token_conflicting_data(recorder, credential_manager):
    sentry_token = credential_manager.sentry_token(2)
    with pytest.raises(Conflict):
        sentry_token.edit(name="sentry_token")


def test_list_sentry_tokens(recorder, credential_manager):
    sentry_tokens = credential_manager.sentry_tokens()
    for sentry_token in sentry_tokens:
        assert isinstance(sentry_token, SentryToken)
