"""Teste US-006 (PRD 5.5): meniu hamburger in header (Cont/Integrare/Nomenclator/Admin/logout)
+ context de autentificare. base.html partajat: pe login/signup meniul nu expune cont/logout.
"""

from __future__ import annotations

import os
import re
import tempfile

import pytest
from starlette.testclient import TestClient


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "menu_test.db"))
    monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "true")
    from app.config import get_settings
    get_settings.cache_clear()
    from app.web import ratelimit
    ratelimit._hits.clear()
    from app.main import app
    with TestClient(app, follow_redirects=False) as c:
        yield c
    ratelimit._hits.clear()
    get_settings.cache_clear()


def _make_user(email="u@test.com", password="parolasecreta10", is_admin=False):
    from app.accounts import create_account
    from app.users import create_user
    from app.db import get_connection
    conn = get_connection()
    try:
        acct_id = create_account(conn, "Service Test", active=True)
        create_user(conn, acct_id, email, password, is_admin=is_admin)
        return acct_id
    finally:
        conn.close()


def _login(client, email="u@test.com", password="parolasecreta10"):
    resp = client.get("/login")
    csrf = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text).group(1)
    resp = client.post("/login", data={"email": email, "parola": password, "csrf_token": csrf})
    assert resp.status_code == 303


def test_meniu_autentificat_are_linkuri_cont(client):
    _make_user()
    _login(client)
    html = client.get("/").text
    # butonul de meniu (hamburger) prezent
    assert 'id="cont-menu-toggle"' in html
    assert 'aria-controls="cont-menu"' in html
    # linkurile mutate in meniu
    assert 'href="/?tab=cont"' in html
    assert 'href="/?tab=integrare"' in html
    assert 'href="/?tab=nomenclator"' in html
    # logout in meniu
    assert 'action="/logout"' in html
    assert "Iesi din cont" in html


def test_meniu_admin_link_doar_pentru_admin(client):
    _make_user(email="admin@test.com", is_admin=True)
    _login(client, email="admin@test.com")
    html = client.get("/").text
    assert 'href="/admin"' in html


def test_meniu_fara_admin_pentru_neadmin(client):
    _make_user(email="plain@test.com", is_admin=False)
    _login(client, email="plain@test.com")
    html = client.get("/").text
    assert 'href="/admin"' not in html


def test_meniu_neautentificat_fara_logout(client):
    """Pe /login (neautentificat) meniul nu expune cont/logout."""
    html = client.get("/login").text
    assert "Iesi din cont" not in html
    assert 'action="/logout"' not in html
    assert 'id="cont-menu-toggle"' not in html
