# retoor <retoor@molodetz.nl>

import requests
from playwright.sync_api import expect
from tests.conftest import BASE_URL
from devplacepy.database import (
    get_notification_default,
    get_notification_prefs,
    get_table,
    notification_enabled,
    reset_notification_prefs,
    set_notification_default,
    set_notification_pref,
)
from devplacepy.utils import create_notification, generate_uid
def _user_notification_prefs(username):
    return get_table("users").find_one(username=username)
def _pref(prefs, key):
    return next(p for p in prefs if p["key"] == key)


def test_admin_default_endpoint(alice):
    _, admin_user = alice
    admin = _user_notification_prefs(admin_user["username"])
    try:
        response = requests.post(
            f"{BASE_URL}/admin/notifications",
            data={"notification_type": "level", "channel": "push", "value": "false"},
            headers={"Accept": "application/json", "X-API-KEY": admin["api_key"]},
            allow_redirects=False,
        )
        assert response.status_code == 200
        assert get_notification_default("level", "push") is False
    finally:
        set_notification_default("level", "push", True)


def test_member_cannot_set_default(bob):
    _, user = bob
    member = _user_notification_prefs(user["username"])
    response = requests.post(
        f"{BASE_URL}/admin/notifications",
        data={"notification_type": "level", "channel": "push", "value": "false"},
        headers={"Accept": "application/json", "X-API-KEY": member["api_key"]},
        allow_redirects=False,
    )
    assert response.status_code in (302, 303, 403)
    assert get_notification_default("level", "push") is True
