import pytest

from credmgr.exceptions import Conflict, NotFound
from credmgr.models import UserVerification


def test_create_user_verification(recorder, credential_manager):
    data = {"user_id": "12345", "reddit_app": 27}
    user_verification = credential_manager.user_verification.create(**data)
    for key, value in data.items():
        if key == "reddit_app":
            assert getattr(user_verification, key).id == value
            continue
        assert getattr(user_verification, key) == value


def test_create_user_verification_full_params(recorder, credential_manager):
    data = {
        "user_id": "1234567",
        "reddit_app": 27,
        "redditor": "redditor",
        "extra_data": {"extra": "data", "nested": {"dict": "value"}},
    }
    user_verification = credential_manager.user_verification.create(**data)
    for key, value in data.items():
        if key == "reddit_app":
            assert getattr(user_verification, key).id == value
            continue
        assert getattr(user_verification, key) == value


def test_create_user_verification_other_user(recorder, credential_manager):
    data = {"user_id": "123456", "reddit_app": 22, "owner": 4}
    user_verification = credential_manager.user_verification.create(**data)
    for key, value in data.items():
        if key in ["owner", "reddit_app"]:
            assert getattr(user_verification, key).id == value
            continue
        assert getattr(user_verification, key) == value


def test_create_user_verification_existing(recorder, credential_manager):
    data = {"user_id": "12345", "reddit_app": 27}
    existing = credential_manager.user_verification.create(**data)
    assert isinstance(existing, UserVerification)
    assert existing.user_id == "12345"


def test_delete_user_verification(recorder, credential_manager):
    user_verification = credential_manager.user_verification("12345")
    user_verification.delete()
    with pytest.raises(NotFound):
        _ = credential_manager.user_verification("12345")


def test_edit_user_verification(recorder, credential_manager):
    user_verification = credential_manager.user_verification("new_id")
    user_verification.edit(redditor="redditor")
    assert user_verification.redditor == "redditor"


def test_edit_user_verification_conflicting_data(recorder, credential_manager):
    user_verification = credential_manager.user_verification("new_id")
    with pytest.raises(Conflict):
        user_verification.edit(user_id="12345")


def test_list_user_verifications(recorder, credential_manager):
    user_verifications = credential_manager.user_verifications()
    for user_verification in user_verifications:
        assert isinstance(user_verification, UserVerification)
