# Tests for iteration 6: POST /api/bulk-delete (to Recycle bin) and per-user saved filters (/api/filters)
# NOTE: never include the real task 'File reply' (id 1). Only TEST_ tasks, filters and users are created and cleaned up.
import json
import re
import uuid

import psycopg
import pytest
import requests

from test_history_reminders import API, ENV, HX, ADMIN, login, ids_for


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 tracked():
    d = {"tasks": set(), "titles": []}
    yield d
    s = login(*ADMIN)
    for t in d["tasks"]:
        s.delete(f"{API}/tasks/{t}", headers=HX)
    if d["titles"]:
        db("DELETE FROM todo_history WHERE task_title = ANY(%s)", (d["titles"],))


@pytest.fixture(scope="module")
def admin_filters(admin_id):
    names = []
    yield names
    if names:
        db("DELETE FROM saved_filters WHERE user_id=%s AND name = ANY(%s)", (admin_id, names))


@pytest.fixture(scope="module")
def other_user(admin):
    email = f"test_{uuid.uuid4().hex[:8]}@example.com"
    r = admin.post(f"{API}/admin/approved", data={"email": email}, allow_redirects=False)
    assert r.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, r.text[:300]
    yield s, email
    admin.post(f"{API}/admin/revoke", data={"email": email}, allow_redirects=False)  # deletes user + cascades filters


def make(s, tracked):
    title = f"TEST_bd_{uuid.uuid4().hex[:6]}"
    r = s.post(f"{API}/tasks", data={"title": title, "color": "green", "assignee": "TEST_Bob"}, headers=HX)
    assert r.status_code == 200
    ids = ids_for(s, title)
    assert len(ids) == 1
    tracked["tasks"].add(ids[0])
    tracked["titles"].append(title)
    return ids[0], title


def filters_html(s):
    r = s.get(f"{API}/filters", headers=HX)
    assert r.status_code == 200
    return r.text


def filter_id(user_id, name):
    rows = db("SELECT id FROM saved_filters WHERE user_id=%s AND name=%s", (user_id, name))
    return rows[0][0] if rows else None


# ---- bulk delete ----
class TestBulkDelete:
    def test_requires_login(self):
        r = requests.post(f"{API}/bulk-delete", data={"ids": "999999999"}, headers=HX, allow_redirects=False)
        assert r.status_code == 401

    @pytest.mark.parametrize("ids", ["", " , ", "abc", "1.5", ",".join(str(10**8 + i) for i in range(1001))])
    def test_bad_ids_400(self, admin, ids):
        r = admin.post(f"{API}/bulk-delete", data={"ids": ids}, headers=HX)
        assert r.status_code == 400

    def test_bulk_delete_to_bin_and_restore_each(self, admin, tracked):
        made = [make(admin, tracked) for _ in range(3)]
        tids = [t for t, _ in made]
        # set a colour on one so it has history to keep
        admin.post(f"{API}/tasks/{tids[0]}/color", data={"color": "red"}, headers=HX)
        missing = 10**9 + 7
        r = admin.post(f"{API}/bulk-delete", data={"ids": ",".join(map(str, tids + [missing]))}, headers=HX)
        assert r.status_code == 200
        t = trig(r)
        assert t["toast"] == "Deleted 3 tasks · restore from the Recycle bin"
        assert t.get("bulkDone") and t.get("tasksChanged")
        assert db("SELECT count(*) FROM todos WHERE id = ANY(%s)", (tids,))[0][0] == 0
        assert db("SELECT count(*) FROM todos WHERE id=1")[0][0] == 1  # real task untouched
        bin_html = admin.get(f"{API}/tasks", params={"view": "bin"}, headers=HX).text
        act_html = admin.get(f"{API}/tasks", params={"view": "activity"}, headers=HX).text
        eids = []
        for tid, title in made:
            eid = db("SELECT id FROM todo_history WHERE orig_todo_id=%s AND field='deleted' ORDER BY id DESC", (tid,))[0][0]
            eids.append(eid)
            assert f'data-testid="bin-row-{eid}"' in bin_html
            assert title in act_html
        # restore each individually
        for (tid, title), eid in zip(made, eids):
            r = admin.post(f"{API}/history/{eid}/restore", headers=HX)
            assert trig(r)["toast"] == f"Restored “{title}”"
            assert ids_for(admin, title) == [tid]
        assert db("SELECT color FROM todos WHERE id=%s", (tids[0],))[0][0] == "red"
        assert db("SELECT count(*) FROM todo_history WHERE todo_id=%s AND field='color'", (tids[0],))[0][0] == 1

    def test_single_and_missing_only(self, admin, tracked):
        tid, _ = make(admin, tracked)
        r = admin.post(f"{API}/bulk-delete", data={"ids": str(tid)}, headers=HX)
        assert trig(r)["toast"] == "Deleted 1 task · restore from the Recycle bin"
        r = admin.post(f"{API}/bulk-delete", data={"ids": str(tid)}, headers=HX)
        assert r.status_code == 200 and trig(r)["toast"].startswith("Deleted 0 tasks")


# ---- saved filters ----
class TestSavedFilters:
    def test_requires_login(self):
        assert requests.get(f"{API}/filters", headers=HX, allow_redirects=False).status_code == 401
        assert requests.post(f"{API}/filters", data={"name": "x"}, headers=HX, allow_redirects=False).status_code == 401

    def test_empty_name_400(self, admin):
        assert admin.post(f"{API}/filters", data={"name": "   "}, headers=HX).status_code == 400

    def test_save_list_update_sanitise(self, admin, admin_id, admin_filters):
        name = f"TEST_f_{uuid.uuid4().hex[:6]}"
        admin_filters.append(name)
        r = admin.post(f"{API}/filters", data={"name": f"  {name} ", "q": "TEST_q", "matter": "M-9", "urgency": "red",
                                                "mine": "1", "sort": "title", "desc": "1"}, headers=HX)
        assert r.status_code == 200
        assert trig(r)["toast"] == f"Saved filter “{name}”" and trig(r)["filtersSaved"]
        fid = filter_id(admin_id, name)
        assert fid
        html = filters_html(admin)
        assert f'data-testid="saved-filter-{fid}"' in html and f'saved-filter-remove-{fid}' in html
        m = re.search(rf'title="([^"]*)" data-testid="saved-filter-apply-{fid}"', html)
        assert m and "TEST_q" in m.group(1) and "M-9" in m.group(1) and "my tasks" in m.group(1)
        assert "sorted by Task (reversed)" in m.group(1)
        # same name -> update, with bad urgency/sort sanitised
        r = admin.post(f"{API}/filters", data={"name": name, "urgency": "purple", "sort": "evil;drop", "desc": "x",
                                                "mine": "yes"}, headers=HX)
        assert trig(r)["toast"] == f"Updated filter “{name}”"
        assert filter_id(admin_id, name) == fid
        params = db("SELECT params FROM saved_filters WHERE id=%s", (fid,))[0][0]
        assert params == {"q": "", "matter": "", "urgency": "all", "mine": "", "sort": "deadline", "desc": "0"}

    def test_private_per_user(self, admin, admin_id, admin_filters, other_user):
        s, email = other_user
        name = f"TEST_priv_{uuid.uuid4().hex[:6]}"
        admin_filters.append(name)
        admin.post(f"{API}/filters", data={"name": name, "q": "x"}, headers=HX)
        fid = filter_id(admin_id, name)
        other_html = filters_html(s)
        assert name not in other_html and f"saved-filter-{fid}" not in other_html
        # admin may have shared team filters; other user must have no own (non-team) chips
        assert not re.search(r'class="saved-chip(?! team-chip)', other_html)
        r = s.delete(f"{API}/filters/{fid}", headers=HX)
        assert r.status_code == 200
        assert filter_id(admin_id, name) == fid  # still there
        # other user can use the same name independently
        r = s.post(f"{API}/filters", data={"name": name}, headers=HX)
        assert trig(r)["toast"] == f"Saved filter “{name}”"
        assert name in filters_html(s)
        # admin removes own
        r = admin.delete(f"{API}/filters/{fid}", headers=HX)
        assert trig(r)["toast"] == "Filter removed" and filter_id(admin_id, name) is None

    def test_max_20(self, other_user):
        s, email = other_user
        uid = db("SELECT id FROM users WHERE email=%s", (email,))[0][0]
        have = db("SELECT count(*) FROM saved_filters WHERE user_id=%s", (uid,))[0][0]
        for i in range(20 - have):
            assert s.post(f"{API}/filters", data={"name": f"TEST_m{i}"}, headers=HX).status_code == 200
        r = s.post(f"{API}/filters", data={"name": "TEST_over"}, headers=HX)
        assert r.status_code == 400 and "20" in r.text
        # updating an existing one at the cap still works
        assert s.post(f"{API}/filters", data={"name": "TEST_m0", "q": "y"}, headers=HX).status_code == 200


# ---- regression: #saved-filters sits inside <form hx-target="#table-wrap">; it must target itself ----
def test_saved_filters_div_targets_itself(admin):
    html = admin.get(f"{API}/").text
    m = re.search(r'<div id="saved-filters"[^>]*>', html)
    assert m and 'hx-target="this"' in m.group(0)
