import re

import pytest

from tests.conftest import TEST_ENCRYPTION_KEY, login, make_config


@pytest.fixture
def csrf_app(tmp_path):
    from app import create_app
    application = create_app(make_config(tmp_path, WTF_CSRF_ENABLED=True))
    from flask_migrate import upgrade
    with application.app_context():
        upgrade()
    yield application
    from app import db
    from flask_migrate import downgrade
    with application.app_context():
        db.session.remove()
        downgrade(revision="base")
        db.engine.dispose()


def _csrf_token(client, account_id):
    login(client, account_id)
    text = client.get("/accounts").get_data(as_text=True)
    match = re.search(r'name="csrf_token" value="([^"]+)"', text)
    assert match, "no csrf token found on /accounts"
    return match.group(1)


def test_mutation_without_token_is_rejected(csrf_app, account):
    client = csrf_app.test_client()
    login(client, account)
    r = client.post("/accounts/%s/activate" % account)
    assert r.status_code == 400


def test_mutation_with_token_succeeds(csrf_app, account):
    client = csrf_app.test_client()
    token = _csrf_token(client, account)
    r = client.post("/accounts/%s/activate" % account, data={"csrf_token": token})
    assert r.status_code == 302


def test_new_post_without_token_is_rejected(csrf_app, account):
    client = csrf_app.test_client()
    login(client, account)
    r = client.post("/posts/new", data={"video_url": "https://x/v.mp4"})
    assert r.status_code == 400


def test_logout_is_post_only(csrf_app, account):
    client = csrf_app.test_client()
    token = _csrf_token(client, account)
    r = client.post("/logout", data={"csrf_token": token})
    assert r.status_code == 302
    r = client.get("/dashboard")
    assert r.status_code == 302
