# Tests for iteration 5: Recycle bin view (view=bin + restore) and bulk actions POST /api/tasks/bulk
# NOTE: never include the real task 'File reply' (id 1) in bulk calls. Only TEST_ tasks are touched.
import json
import re
import uuid
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

import psycopg
import pytest
import requests

from test_history_reminders import API, ENV, HX, ADMIN, login, ids_for

TODAY = datetime.now(ZoneInfo("America/New_York")).date()
FUT = TODAY + timedelta(days=5)


@pytest.fixture(scope="module")
def admin():
    return login(*ADMIN)


@pytest.fixture(scope="module")
def tracked():
    d = {"tasks": set(), "titles": []}
    yield d
    s = login(*ADMIN)
    with psycopg.connect(ENV["DATABASE_URL"], autocommit=True) as c:
        for title in d["titles"]:
            for (tid,) in c.execute("SELECT id FROM todos WHERE title=%s", (title,)).fetchall():
                d["tasks"].add(tid)
    for t in d["tasks"]:
        s.delete(f"{API}/tasks/{t}", headers=HX)
    with psycopg.connect(ENV["DATABASE_URL"], autocommit=True) as c:
        if d["titles"]:
            c.execute("DELETE FROM todo_history WHERE task_title = ANY(%s)", (d["titles"],))
            c.execute("DELETE FROM overdue_alerts WHERE todo_id = ANY(%s)", (list(d["tasks"]),))


def make(s, tracked, **data):
    title = data.setdefault("title", f"TEST_b_{uuid.uuid4().hex[:6]}")
    data.setdefault("color", "green")
    r = s.post(f"{API}/tasks", data=data, 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 trig(r):
    return json.loads(r.headers.get("HX-Trigger", "{}"))


def task(tid):
    from psycopg.rows import dict_row
    with psycopg.connect(ENV["DATABASE_URL"], row_factory=dict_row) as c:
        row = c.execute("SELECT color, assignee, deadline, title, notes, matter_no FROM todos WHERE id=%s", (tid,)).fetchone()
    return row


def hist(tid, field):
    with psycopg.connect(ENV["DATABASE_URL"]) as c:
        return c.execute("SELECT old_value, new_value, changed_by FROM todo_history WHERE todo_id=%s AND field=%s ORDER BY id",
                         (tid, field)).fetchall()


def bulk(s, ids, action, value=""):
    return s.post(f"{API}/tasks/bulk", data={"ids": ",".join(map(str, ids)), "action": action, "value": value}, headers=HX)


# ---- bulk validation ----
class TestBulkValidation:
    def test_requires_login(self):
        r = requests.post(f"{API}/tasks/bulk", data={"ids": "999999", "action": "color", "value": "red"},
                          headers=HX, allow_redirects=False)
        assert r.status_code in (401, 302, 303, 307)
        assert task(1)["color"] == "yellow"

    @pytest.mark.parametrize("ids,action,value", [
        ("abc", "color", "red"), ("", "color", "red"), (",", "color", "red"),
        ("999999", "nope", "x"), ("999999", "color", "purple"), ("999999", "deadline", "2026-13-40"),
        ("999999", "deadline", "tomorrow"),
    ])
    def test_400(self, admin, ids, action, value):
        r = admin.post(f"{API}/tasks/bulk", data={"ids": ids, "action": action, "value": value}, headers=HX)
        assert r.status_code == 400, (ids, action, value, r.status_code, r.text)

    def test_missing_ids_reported(self, admin):
        r = bulk(admin, [999998, 999999], "color", "red")
        assert r.status_code == 200
        assert trig(r)["toast"] == "Set 0 tasks to Urgent non-extendable (2 no longer exist)"
        r = bulk(admin, [999999], "color", "red")
        assert trig(r)["toast"].endswith("(1 no longer exists)")
        assert trig(r).get("bulkDone") is True


# ---- bulk actions ----
class TestBulkActions:
    def test_color(self, admin, tracked):
        a, _ = make(admin, tracked, color="green")
        b, _ = make(admin, tracked, color="red")
        c, _ = make(admin, tracked, color="blue")
        r = bulk(admin, [a, b, c], "color", "red")
        t = trig(r)
        assert t["toast"] == "Set 2 tasks to Urgent non-extendable", t
        assert t.get("tasksChanged") is True
        assert all(task(i)["color"] == "red" for i in (a, b, c))
        assert len(hist(a, "color")) == 1 and hist(a, "color")[0][1] == "Urgent non-extendable"
        assert hist(b, "color") == []
        assert task(1)["color"] == "yellow"
        # singular
        r = bulk(admin, [a, b, c], "color", "orange")
        assert trig(r)["toast"] == "Set 3 tasks to Very important"
        r = bulk(admin, [a], "color", "green")
        assert trig(r)["toast"] == "Set 1 task to OK"

    def test_assignee_set_and_clear(self, admin, tracked):
        a, _ = make(admin, tracked, assignee="Bob")
        b, _ = make(admin, tracked)
        r = bulk(admin, [a, b], "assignee", "  TEST_ Carol   Smith ")
        assert trig(r)["toast"] == "Set 2 tasks to assignee TEST_ Carol Smith"
        assert task(a)["assignee"] == "TEST_ Carol Smith" and task(b)["assignee"] == "TEST_ Carol Smith"
        assert hist(a, "assignee")[-1][:2] == ("Bob", "TEST_ Carol Smith")
        r = bulk(admin, [a, b], "assignee", "")
        assert trig(r)["toast"] == "Set 2 tasks to no assignee"
        assert task(a)["assignee"] == "" and task(b)["assignee"] == ""

    def test_deadline_set_and_clear(self, admin, tracked):
        a, _ = make(admin, tracked)
        b, _ = make(admin, tracked, deadline=FUT.isoformat())
        r = bulk(admin, [a, b], "deadline", FUT.isoformat())
        assert trig(r)["toast"] == f"Set 1 task to {FUT.strftime('%a %d %b %Y')}"
        assert task(a)["deadline"] == FUT
        r = bulk(admin, [a, b], "deadline", "")
        assert trig(r)["toast"] == "Set 2 tasks to no deadline"
        assert task(a)["deadline"] is None and task(b)["deadline"] is None
        assert hist(b, "deadline")[-1][:2] == (FUT.isoformat(), "")

    def test_mixed_existing_and_missing_and_dupes(self, admin, tracked):
        a, _ = make(admin, tracked)
        r = bulk(admin, [a, a, 999999], "color", "blue")
        assert trig(r)["toast"] == "Set 1 task to Not urgent (1 no longer exists)"


# ---- recycle bin ----
class TestBin:
    def bin_html(self, s):
        r = s.get(f"{API}/tasks", params={"view": "bin"}, headers=HX)
        assert r.status_code == 200
        return r.text

    def test_bin_requires_login(self):
        r = requests.get(f"{API}/tasks", params={"view": "bin"}, allow_redirects=False)
        assert r.status_code in (401, 302, 303, 307)

    def test_delete_shows_in_bin_restore_and_redelete(self, admin, tracked):
        tid, title = make(admin, tracked, assignee="TEST_Ann", matter_no="TM-9", notes="TEST note x",
                          deadline=FUT.isoformat(), color="orange")
        bulk(admin, [tid], "color", "red")
        admin.delete(f"{API}/tasks/{tid}", headers=HX)
        html = self.bin_html(admin)
        with psycopg.connect(ENV["DATABASE_URL"]) as c:
            eid = c.execute("SELECT id FROM todo_history WHERE orig_todo_id=%s AND field='deleted' ORDER BY id DESC",
                            (tid,)).fetchone()[0]
        m = re.search(rf'data-testid="bin-row-{eid}".*?</tr>', html, re.S)
        assert m, "row missing in bin"
        row = m.group(0)
        for s in (title, "TEST_Ann", "TM-9", "TEST note x", FUT.isoformat(), "Urgent non-extendable", f"bin-restore-{eid}"):
            assert s in row, s
        assert "bin-count" in html
        # newest first
        tid2, title2 = make(admin, tracked)
        admin.delete(f"{API}/tasks/{tid2}", headers=HX)
        html = self.bin_html(admin)
        assert html.index(title2) < html.index(title)
        # restore
        r = admin.post(f"{API}/history/{eid}/restore", headers=HX)
        assert trig(r)["toast"] == f"Restored “{title}”"
        t = task(tid)
        assert t and t["color"] == "red" and t["assignee"] == "TEST_Ann" and t["deadline"] == FUT
        assert len(hist(tid, "color")) == 1  # history re-linked
        assert f"bin-row-{eid}" not in self.bin_html(admin)
        r = admin.post(f"{API}/history/{eid}/restore", headers=HX)
        assert trig(r)["toast"] == "This task was already restored"
        # delete again -> back in bin with new entry
        admin.delete(f"{API}/tasks/{tid}", headers=HX)
        html = self.bin_html(admin)
        with psycopg.connect(ENV["DATABASE_URL"]) as c:
            eid2 = c.execute("SELECT id FROM todo_history WHERE orig_todo_id=%s AND field='deleted' ORDER BY id DESC",
                             (tid,)).fetchone()[0]
        assert eid2 != eid and f"bin-row-{eid2}" in html

    def test_old_entries_excluded(self, admin, tracked):
        tid, title = make(admin, tracked)
        admin.delete(f"{API}/tasks/{tid}", headers=HX)
        with psycopg.connect(ENV["DATABASE_URL"], autocommit=True) as c:
            c.execute("UPDATE todo_history SET changed_at = now() - interval '31 days' WHERE orig_todo_id=%s AND field='deleted'",
                      (tid,))
        assert title not in self.bin_html(admin)
