import pylibrus.exceptions
from pylibrus.api import base_post_rq


async def user_credentials(username, password, long_lived=True):
    res = await base_post_rq("/OAuth/Token", body={
        "username": username,
        "password": password,
        "grant_type": "password",
        "librus_long_term_token": int(long_lived),
    })
    if res.status_code != 200:
        raise pylibrus.exceptions.InvalidCredentials("Invalid credentials.")
    token_data = res.json()
    return token_data["access_token"], token_data["refresh_token"]

async def refresh_token(refresh_token_value: str, long_lived: bool = True):
    res = await base_post_rq("/OAuth/Token", body={
        "refresh_token": refresh_token_value,
        "grant_type": "refresh_token",
        "librus_long_term_token": int(long_lived),
    })
    if res.status_code != 200:
        raise pylibrus.exceptions.InvalidCredentials("Invalid refresh token.")
    token_data = res.json()
    return token_data["access_token"], token_data["refresh_token"]
