# retoor <retoor@molodetz.nl>

import time
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table
_counter_follow_api = [0]
def _session_follow_api():
    _counter_follow_api[0] += 1
    name = f"flw{int(time.time() * 1000)}{_counter_follow_api[0]}"
    s = requests.Session()
    s.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 s, name
def _uid_follow_api(username):
    return get_table("users").find_one(username=username)["uid"]


def test_unfollow_removes_follow(app_server):
    s_a, a_name = _session_follow_api()
    _, b_name = _session_follow_api()
    a_uid, b_uid = _uid_follow_api(a_name), _uid_follow_api(b_name)

    s_a.post(f"{BASE_URL}/follow/{b_name}", allow_redirects=False)
    s_a.post(f"{BASE_URL}/follow/unfollow/{b_name}", allow_redirects=False)
    assert (
        get_table("follows").count(
            follower_uid=a_uid, following_uid=b_uid, deleted_at=None
        )
        == 0
    )

    r = s_a.post(f"{BASE_URL}/follow/unfollow/{b_name}", allow_redirects=False)
    assert r.status_code == 302
