# retoor <retoor@molodetz.nl>

import time
import requests
from playwright.sync_api import expect
from tests.conftest import BASE_URL
from devplacepy.database import (
    CUSTOMIZATION_GLOBAL_SCOPE,
    get_customization_prefs,
    get_table,
    list_custom_overrides,
    set_custom_override,
    set_customization_pref,
)
from devplacepy.utils import clear_user_cache
def _user_customization_toggle(username):
    return get_table("users").find_one(username=username)
def _seed_global_css(uid, sentinel):
    set_custom_override(
        "user", uid, CUSTOMIZATION_GLOBAL_SCOPE, "css", f".{sentinel} {{ color: red; }}"
    )
def _profile(page, username):
    page.goto(f"{BASE_URL}/profile/{username}", wait_until="domcontentloaded")
def _click_toggle(page, category):
    page.locator(f"[data-customization-toggle='{category}']").click()
    page.locator(".dialog-overlay.visible .dialog-confirm").click()


def test_owner_sees_toggles_and_initial_state(bob):
    page, user = bob
    uid = _user_customization_toggle(user["username"])["uid"]
    set_customization_pref(uid, "global", disabled=False)
    set_customization_pref(uid, "pagetype", disabled=False)
    _seed_global_css(uid, "owner-sees-toggle")

    _profile(page, user["username"])
    expect(page.locator("[data-customization]")).to_be_visible()
    expect(page.locator("[data-customization-toggle='global']")).to_have_text("Disable")
    expect(page.locator("[data-customization-toggle='pagetype']")).to_have_text(
        "Disable"
    )


def test_disable_keeps_rows(bob):
    page, user = bob
    uid = _user_customization_toggle(user["username"])["uid"]
    set_customization_pref(uid, "global", disabled=False)
    _seed_global_css(uid, "keep-rows")

    _profile(page, user["username"])
    _click_toggle(page, "global")
    expect(page.locator("[data-customization-toggle='global']")).to_have_text("Enable")

    rows = [
        r
        for r in list_custom_overrides("user", uid)
        if r["scope"] == CUSTOMIZATION_GLOBAL_SCOPE
    ]
    assert rows, "disabling must not delete the stored override row"


def test_admin_operates_on_other_user(alice, seeded_db):
    admin_page, admin_user = alice
    target = _user_customization_toggle(seeded_db["bob"]["username"])
    admin_uid = _user_customization_toggle(admin_user["username"])["uid"]
    get_table("users").update({"uid": admin_uid, "role": "Admin"}, ["uid"])
    clear_user_cache(admin_uid)
    set_customization_pref(target["uid"], "global", disabled=False)

    _profile(admin_page, target["username"])
    expect(admin_page.locator("[data-customization]")).to_be_visible()
    _click_toggle(admin_page, "global")
    expect(
        admin_page.locator("[data-customization-toggle='global']")
    ).to_have_text("Enable")

    assert get_customization_prefs("user", target["uid"])["disable_global"] is True
