#!/usr/bin/env python3

from tentacles.db import Db


def test_mkuser(db: Db, username_testy, password_testy):
    res = db.try_create_user(
        username=username_testy, email=username_testy, password=password_testy
    )
    assert res
    assert [(it.id, it.name) for it in db.list_users()] == [(res.id, username_testy)]


def test_mksession(db: Db, uid_testy, username_testy, password_testy, login_ttl):
    assert uid_testy
    res = db.try_login(username=username_testy, password=password_testy, ttl=login_ttl)
    assert res is not None
    assert [it.id for it in db.list_keys(uid=uid_testy)] == [res.id]
    assert db.try_key(kid=res.id).user_id == uid_testy


def test_refresh_key(db: Db, sid_testy, login_ttl):
    before = db.fetch_key(kid=sid_testy)
    db.refresh_key(kid=sid_testy, ttl=login_ttl * 2)
    after = db.fetch_key(kid=sid_testy)
    assert before != after


def tets_mkkey(db: Db, sid_testy, uid_testy):
    assert db.try_key(kid=sid_testy) == uid_testy
    new_key = db.create_key(kid=sid_testy, ttl=None)
    assert new_key is not None
    assert db.try_key(kid=new_key) == uid_testy


def test_logout(db: Db, uid_testy, sid_testy):
    assert db.try_key(kid=sid_testy)
    db.delete_key(uid=uid_testy, kid=sid_testy)
    assert not db.try_key(kid=sid_testy)
