import http

import pytest

from h2o_secure_store.clients.oauth_client.oauth_client import OAuthClient
from h2o_secure_store.clients.token_source.client import TokenSourceClient
from h2o_secure_store.exception import CustomApiException


def test_create_token_source(
    delete_all_token_sources_before_after,
    oauth_client1: OAuthClient,
    user_token_source_client: TokenSourceClient,
):
    token_source = user_token_source_client.create_token_source(
        oauth_client_id=oauth_client1.oauth_client_id,
        redirect_uri="http://localhost:8080",
        token_source_id="token-source1",
    )

    assert token_source.token_source_id == "token-source1"
    assert token_source.oauth_client_id == "oauth-client1"
    assert token_source.name == "oauthClients/oauth-client1/tokenSources/token-source1"
    assert token_source.creator != ""
    assert token_source.create_time is not None
    assert token_source.login_time is None
    assert token_source.login_required is True
    assert token_source.login_uri is not None
    assert token_source.redirect_uri is not None
    assert token_source.uid != ""


def test_create_token_source_already_exists(
    delete_all_token_sources_before_after,
    oauth_client1: OAuthClient,
    user_token_source_client: TokenSourceClient,
):
    user_token_source_client.create_token_source(
        oauth_client_id=oauth_client1.oauth_client_id,
        redirect_uri="http://localhost:8080",
        token_source_id="token-source-2",
    )

    with pytest.raises(CustomApiException) as exc:
        user_token_source_client.create_token_source(
            oauth_client_id=oauth_client1.oauth_client_id,
            redirect_uri="http://localhost:8080",
            token_source_id="token-source-2",
        )

    # grpc AlreadyExists == http Conflict 409
    assert exc.value.status == http.HTTPStatus.CONFLICT


def test_create_token_source_autogenerated_id(
    delete_all_token_sources_before_after,
    oauth_client1: OAuthClient,
    user_token_source_client: TokenSourceClient,
):
    token_source = user_token_source_client.create_token_source(
        oauth_client_id=oauth_client1.oauth_client_id,
        redirect_uri="http://localhost:8080",
        token_source_id="token-source-3",
    )
    assert token_source.token_source_id != ""

