from app import db
from app.models import Account
from tests.conftest import add_account


def test_tokens_are_encrypted_at_rest(app, account):
    with app.app_context():
        row = db.session.get(Account, account)
        assert row._access_token != "access-token-plain"
        assert row._refresh_token != "refresh-token-plain"
        assert row.access_token_plain() == "access-token-plain"
        assert row.refresh_token_plain() == "refresh-token-plain"


def test_to_dict_never_contains_tokens(app, account):
    import json
    with app.app_context():
        row = db.session.get(Account, account)
        data = json.dumps(row.to_dict())
        assert "access-token-plain" not in data
        assert "refresh-token-plain" not in data
        assert row.to_dict()["follower_count"] == 1000
        assert row.scope_list() == ["user.info.basic", "video.list", "video.upload", "video.publish"]


def test_token_expiry_flag(app, account):
    from datetime import datetime, timedelta, timezone
    with app.app_context():
        row = db.session.get(Account, account)
        assert row.token_is_expired() is False
        row.expires_at = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(minutes=1)
        assert row.token_is_expired() is True
        row.expires_at = None
        assert row.token_is_expired() is True


def test_second_account(app, account):
    second = add_account(app, open_id="open_id_0002", name="Second Account")
    with app.app_context():
        rows = db.session.query(Account).order_by(Account.open_id).all()
        assert len(rows) == 2
        assert {r.open_id for r in rows} == {"open_id_0001", "open_id_0002"}
    assert second != account
