# Tests for iteration 7: shared team filters (admin share), per-user default filter, GET / redirect
# Only TEST_ filters/users are created and cleaned up. Admin's default is cleared at teardown.
import json
import re
import uuid

import psycopg
import pytest
import requests

from test_history_reminders import API, ENV, HX, ADMIN, login

BASE = API[:-4]


def trig(r):
    return json.loads(r.headers.get("HX-Trigger", "{}"))


def db(sql, args=()):
    with psycopg.connect(ENV["DATABASE_URL"], autocommit=True) as c:
        cur = c.execute(sql, args)
        return cur.fetchall() if cur.description else None


@pytest.fixture(scope="module")
def admin():
    return login(*ADMIN)


@pytest.fixture(scope="module")
def admin_id():
    return db("SELECT id FROM users WHERE email=%s", (ADMIN[0],))[0][0]


@pytest.fixture(scope="module")
def ctx(admin, admin_id):
    d = {"fids": []}
    prev_default = db("SELECT default_filter_id FROM users WHERE id=%s", (admin_id,))[0][0]
    yield d
    for fid in d["fids"]:
        admin.delete(f"{API}/filters/{fid}", headers=HX)
    db("UPDATE users SET default_filter_id=%s WHERE id=%s AND default_filter_id IS NULL", (prev_default, admin_id))


@pytest.fixture(scope="module")
def other(admin):
    email = f"test_{uuid.uuid4().hex[:8]}@example.com"
    assert admin.post(f"{API}/admin/approved", data={"email": email}, allow_redirects=False).status_code == 303
    s = requests.Session()
    r = s.post(f"{API}/register", data={"name": "TEST_Other", "email": email, "password": "TESTpass123"},
               allow_redirects=False)
    assert r.status_code == 303
    uid = db("SELECT id FROM users WHERE email=%s", (email,))[0][0]
    yield s, uid
    admin.post(f"{API}/admin/revoke", data={"email": email}, allow_redirects=False)


def save(s, user_id, name, **params):
    r = s.post(f"{API}/filters", data={"name": name, **params}, headers=HX)
    assert r.status_code == 200
    return db("SELECT id FROM saved_filters WHERE user_id=%s AND name=%s", (user_id, name))[0][0]


def flist(s):
    r = s.get(f"{API}/filters", headers=HX)
    assert r.status_code == 200
    return r.text


def chip(html, fid):
    m = re.search(rf'<span class="([^"]*)" data-filter-id="{fid}".*?</span>\s*\n</span>', html, re.S)
    if not m:
        m = re.search(rf'<span class="([^"]*)" data-filter-id="{fid}"(.*?)(?=<span class="saved-chip|\Z)', html, re.S)
    return m


def test_root_redirect():
    # preview ingress routes "/" to port 3000, so check the backend directly
    r = requests.get("http://localhost:8001/", allow_redirects=False)
    assert r.status_code in (302, 303, 307) and r.headers["location"].endswith("/api/")


def test_share_requires_admin_and_owner(admin, admin_id, other, ctx):
    s, uid = other
    fid = save(admin, admin_id, f"TEST_sh_{uuid.uuid4().hex[:6]}", urgency="red")
    ctx["fids"].append(fid)
    ofid = save(s, uid, "TEST_mine", q="zz")
    assert s.post(f"{API}/filters/{fid}/share", headers=HX).status_code == 403
    assert s.post(f"{API}/filters/{ofid}/share", headers=HX).status_code == 403
    assert admin.post(f"{API}/filters/{ofid}/share", headers=HX).status_code == 404
    assert db("SELECT shared FROM saved_filters WHERE id=%s", (ofid,))[0][0] is False
    assert requests.post(f"{API}/filters/{fid}/share", headers=HX, allow_redirects=False).status_code == 401
    # non-admin html has no share buttons
    assert "saved-filter-share-" not in flist(s)
    assert f"saved-filter-share-{fid}" in flist(admin)


def test_share_toggle_and_team_view(admin, admin_id, other, ctx):
    s, uid = other
    name = f"TEST_team_{uuid.uuid4().hex[:6]}"
    fid = save(admin, admin_id, name, urgency="red", sort="title", desc="1")
    ctx["fids"].append(fid)
    assert name not in flist(s)
    r = admin.post(f"{API}/filters/{fid}/share", headers=HX)
    assert r.status_code == 200 and trig(r)["toast"] == f"“{name}” is now shared with the team" and trig(r)["filtersSaved"]
    ah = flist(admin)
    assert re.search(rf'data-testid="saved-filter-apply-{fid}">{name}<span class="team-tag">Shared</span>', ah)
    assert re.search(rf'data-testid="saved-filter-share-{fid}">Unshare<', ah)
    oh = flist(s)
    assert re.search(rf'saved-chip team-chip[^"]*" data-filter-id="{fid}"', oh)
    assert re.search(rf'· shared by [^"]+" data-testid="saved-filter-apply-{fid}">{name}<span class="team-tag">Team</span>', oh)
    assert f"saved-filter-remove-{fid}" not in oh and f"saved-filter-share-{fid}" not in oh
    assert f"saved-filter-default-{fid}" in oh
    # own private filters of other user stay private from admin
    assert "TEST_mine" not in ah
    # other user cannot delete
    assert s.delete(f"{API}/filters/{fid}", headers=HX).status_code == 200
    assert db("SELECT count(*) FROM saved_filters WHERE id=%s", (fid,))[0][0] == 1
    # unshare
    r = admin.post(f"{API}/filters/{fid}/share", headers=HX)
    assert trig(r)["toast"] == f"“{name}” is now private"
    assert name not in flist(s)
    assert re.search(rf'data-testid="saved-filter-share-{fid}">Share<', flist(admin))


def test_default_toggle_single_and_index(admin, admin_id, ctx):
    a = save(admin, admin_id, f"TEST_da_{uuid.uuid4().hex[:6]}", q="TEST_zzq", urgency="orange", mine="1",
             sort="title", desc="1")
    b = save(admin, admin_id, f"TEST_db_{uuid.uuid4().hex[:6]}", matter="M-1")
    ctx["fids"] += [a, b]
    r = admin.post(f"{API}/filters/{a}/default", headers=HX)
    assert r.status_code == 200 and "will open when you sign in" in trig(r)["toast"]
    h = flist(admin)
    assert re.search(rf'is-default" data-filter-id="{a}"', h)
    assert re.search(rf'data-testid="saved-filter-default-{a}">★<', h)
    idx = admin.get(f"{API}/").text
    assert f'data-default-id="{a}"' in idx and "TEST_zzq" in idx
    # switch to b -> only one default
    admin.post(f"{API}/filters/{b}/default", headers=HX)
    assert db("SELECT default_filter_id FROM users WHERE id=%s", (admin_id,))[0][0] == b
    h = flist(admin)
    assert h.count("is-default") == 1 and re.search(rf'data-testid="saved-filter-default-{a}">☆<', h)
    # click again clears
    r = admin.post(f"{API}/filters/{b}/default", headers=HX)
    assert trig(r)["toast"] == "No filter opens automatically now"
    assert db("SELECT default_filter_id FROM users WHERE id=%s", (admin_id,))[0][0] is None
    assert "data-default-id" not in admin.get(f"{API}/").text
    # unknown filter
    assert admin.post(f"{API}/filters/999999999/default", headers=HX).status_code == 404


def test_team_default_then_unshare_and_delete(admin, admin_id, other, ctx):
    s, uid = other
    fid = save(admin, admin_id, f"TEST_td_{uuid.uuid4().hex[:6]}", urgency="red")
    ctx["fids"].append(fid)
    # cannot default a private filter of someone else
    assert s.post(f"{API}/filters/{fid}/default", headers=HX).status_code == 404
    admin.post(f"{API}/filters/{fid}/share", headers=HX)
    assert s.post(f"{API}/filters/{fid}/default", headers=HX).status_code == 200
    assert f'data-default-id="{fid}"' in s.get(f"{API}/").text
    # unshare -> nothing applied, no error
    admin.post(f"{API}/filters/{fid}/share", headers=HX)
    r = s.get(f"{API}/")
    assert r.status_code == 200 and "data-default-id" not in r.text
    assert s.get(f"{API}/filters", headers=HX).status_code == 200
    # reshare then delete -> FK set null
    admin.post(f"{API}/filters/{fid}/share", headers=HX)
    admin.delete(f"{API}/filters/{fid}", headers=HX)
    assert db("SELECT default_filter_id FROM users WHERE id=%s", (uid,))[0][0] is None
    r = s.get(f"{API}/")
    assert r.status_code == 200 and "data-default-id" not in r.text
