import pytest
from pydantic import ValidationError

from delta_barth.api import common
from delta_barth.errors import (
    UnspecifiedRequestType,
)
from delta_barth.types import HttpRequestTypes


def test_validate_creds(credentials):
    creds = common.validate_credentials(
        username=credentials["user"],
        password=credentials["pwd"],
        database=credentials["db"],
        mandant=credentials["mandant"],
    )
    assert creds.username == credentials["user"]
    assert creds.password == credentials["pwd"]
    assert creds.database == credentials["db"]
    assert creds.mandant == credentials["mandant"]
    # with whitespaces
    user = "  " + credentials["user"] + " "
    creds = common.validate_credentials(
        username=user,
        password=credentials["pwd"],
        database=credentials["db"],
        mandant=credentials["mandant"],
    )
    assert user != credentials["user"]
    assert creds.username == credentials["user"]
    # invalid type
    user = 123
    with pytest.raises(ValidationError):
        creds = common.validate_credentials(
            username=user,  # type: ignore
            password=credentials["pwd"],
            database=credentials["db"],
            mandant=credentials["mandant"],
        )


@pytest.mark.api_con_required
def test_ping(api_base_url):
    resp = common.ping(api_base_url, HttpRequestTypes.GET)
    assert resp.status_code == 204
    resp = common.ping(api_base_url, HttpRequestTypes.PUT)
    assert resp.status_code == 204
    resp = common.ping(api_base_url, HttpRequestTypes.DELETE)
    assert resp.status_code == 204

    with pytest.raises(UnspecifiedRequestType):
        resp = common.ping(api_base_url, HttpRequestTypes.POST)
