# retoor <retoor@molodetz.nl>

import time
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table

JSON = {"Accept": "application/json"}
_counter = [0]


def _signup():
    _counter[0] += 1
    name = f"unmut{int(time.time() * 1000)}{_counter[0]}"
    session = requests.Session()
    session.post(
        f"{BASE_URL}/auth/signup",
        data={
            "username": name,
            "email": f"{name}@t.dev",
            "password": "secret123",
            "confirm_password": "secret123",
            "birth_date": "1990-01-01",
            "accept_terms": "1",
        },
        allow_redirects=True,
    )
    return session, name


def _uid(name):
    return get_table("users").find_one(username=name)["uid"]


def _active_mutes(actor_uid, target_uid):
    return get_table("user_relations").count(
        user_uid=actor_uid, target_uid=target_uid, kind="mute", deleted_at=None
    )


def test_unmute_reverses_mute(app_server):
    muter_session, muter = _signup()
    _, target = _signup()
    muter_session.post(f"{BASE_URL}/mute/{target}", allow_redirects=False)
    assert _active_mutes(_uid(muter), _uid(target)) == 1

    r = muter_session.post(
        f"{BASE_URL}/mute/unmute/{target}", allow_redirects=False
    )
    assert r.status_code in (302, 200)
    assert _active_mutes(_uid(muter), _uid(target)) == 0


def test_unmute_restores_notifications(app_server):
    muter_session, muter = _signup()
    actor_session, actor = _signup()
    muter_session.post(f"{BASE_URL}/mute/{actor}", allow_redirects=False)
    muter_session.post(f"{BASE_URL}/mute/unmute/{actor}", allow_redirects=False)

    actor_session.post(f"{BASE_URL}/follow/{muter}", allow_redirects=False)

    assert (
        get_table("notifications").count(
            user_uid=_uid(muter), related_uid=_uid(actor), type="follow"
        )
        == 1
    )
