# retoor <retoor@molodetz.nl>

import time
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table
DEFAULT_MAINTENANCE_MESSAGE = (
    "DevPlace is undergoing scheduled maintenance. Please check back shortly."
)
OPERATIONAL_FIELDS = (
    "rate_limit_per_minute",
    "rate_limit_window_seconds",
    "session_max_age_days",
    "session_remember_days",
    "registration_open",
    "maintenance_mode",
    "maintenance_message",
)
def _save_settings(page, **fields):
    page.goto(f"{BASE_URL}/admin/settings", wait_until="domcontentloaded")
    for name, value in fields.items():
        locator = page.locator(f"#{name}")
        tag = locator.evaluate("el => el.tagName.toLowerCase()")
        if tag == "select":
            page.select_option(f"#{name}", value)
        else:
            locator.fill(value)
    page.click("button:has-text('Save Settings')")
    page.wait_for_url("**/admin/settings", wait_until="domcontentloaded")


def test_operational_settings_persist(alice):
    page, _ = alice
    try:
        _save_settings(
            page,
            session_remember_days="14",
            maintenance_message="Custom maintenance text",
        )
        assert page.locator("#session_remember_days").input_value() == "14"
        assert (
            page.locator("#maintenance_message").input_value()
            == "Custom maintenance text"
        )
    finally:
        _save_settings(
            page,
            session_remember_days="30",
            maintenance_message=DEFAULT_MAINTENANCE_MESSAGE,
        )
