"""Teste US-009 (PRD 3.5): filtrare/cautare in Trimiteri (stare/vehicul/data).

Toate scoped pe cont, fara leak cross-account.
"""

from __future__ import annotations

import json
import os
import re
import tempfile

import pytest
from starlette.testclient import TestClient


def _create_account_user(email: str, name: str = "Service", password: str = "parolasecreta10"):
    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, name, active=True)
        create_user(conn, acct_id, email, password)
        return acct_id
    finally:
        conn.close()


def _login(client, email: str, password: str = "parolasecreta10") -> None:
    resp = client.get("/login")
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text) or \
        re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
    assert m
    resp = client.post("/login", data={"email": email, "parola": password, "csrf_token": m.group(1)})
    assert resp.status_code == 303


def _ins(acct: int, *, status: str, vin: str, nr: str, data: str) -> int:
    from app.db import get_connection
    conn = get_connection()
    try:
        cur = conn.execute(
            "INSERT INTO submissions (idempotency_key, account_id, status, payload_json) VALUES (?, ?, ?, ?)",
            (
                f"k-{os.urandom(5).hex()}", acct, status,
                json.dumps({"vin": vin, "nr_inmatriculare": nr, "data_prestatie": data,
                            "odometru_final": "100", "prestatii": [{"cod_prestatie": "R-X"}]}),
            ),
        )
        conn.commit()
        return int(cur.lastrowid)
    finally:
        conn.close()


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "filtre.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 test_filtru_stare(client):
    acct = _create_account_user("fs@test.com")
    sid_q = _ins(acct, status="queued", vin="WVWZZZ1JZXW000001", nr="B001AAA", data="2026-06-10")
    sid_nd = _ins(acct, status="needs_data", vin="WVWZZZ1JZXW000002", nr="B002BBB", data="2026-06-11")
    _login(client, "fs@test.com")

    resp = client.get("/_fragments/submissions?status=needs_data")
    assert resp.status_code == 200
    html = resp.text
    assert f'id="trimitere-row-{sid_nd}"' in html
    assert f'id="trimitere-row-{sid_q}"' not in html


def test_filtru_vehicul(client):
    acct = _create_account_user("fv@test.com")
    sid_a = _ins(acct, status="sent", vin="WVWZZZ1JZXW000111", nr="CJ77ABC", data="2026-06-10")
    sid_b = _ins(acct, status="sent", vin="WVWZZZ1JZXW000222", nr="TM01XYZ", data="2026-06-11")
    _login(client, "fv@test.com")

    # cautare pe nr (case-insensitive)
    resp = client.get("/_fragments/submissions?vehicul=cj77")
    assert resp.status_code == 200
    assert f'id="trimitere-row-{sid_a}"' in resp.text
    assert f'id="trimitere-row-{sid_b}"' not in resp.text

    # cautare pe fragment VIN
    resp = client.get("/_fragments/submissions?vehicul=000222")
    assert f'id="trimitere-row-{sid_b}"' in resp.text
    assert f'id="trimitere-row-{sid_a}"' not in resp.text


def test_filtru_data(client):
    acct = _create_account_user("fd@test.com")
    sid_old = _ins(acct, status="sent", vin="WVWZZZ1JZXW000333", nr="B1", data="2026-06-01")
    sid_new = _ins(acct, status="sent", vin="WVWZZZ1JZXW000444", nr="B2", data="2026-06-20")
    _login(client, "fd@test.com")

    resp = client.get("/_fragments/submissions?data_de=2026-06-15")
    assert resp.status_code == 200
    assert f'id="trimitere-row-{sid_new}"' in resp.text
    assert f'id="trimitere-row-{sid_old}"' not in resp.text

    resp = client.get("/_fragments/submissions?data_pana=2026-06-10")
    assert f'id="trimitere-row-{sid_old}"' in resp.text
    assert f'id="trimitere-row-{sid_new}"' not in resp.text


def test_filtru_scoped_cross_account(client):
    acct1 = _create_account_user("fc1@test.com", name="C1")
    acct2 = _create_account_user("fc2@test.com", name="C2")
    sid1 = _ins(acct1, status="needs_data", vin="WVWZZZ1JZXW000555", nr="B1", data="2026-06-10")
    sid2 = _ins(acct2, status="needs_data", vin="WVWZZZ1JZXW000666", nr="B2", data="2026-06-10")

    _login(client, "fc2@test.com")
    resp = client.get("/_fragments/submissions?status=needs_data")
    assert f'id="trimitere-row-{sid2}"' in resp.text
    assert f'id="trimitere-row-{sid1}"' not in resp.text


def test_empty_state_filtru_are_buton_sterge(client):
    acct = _create_account_user("fe@test.com")
    _ins(acct, status="sent", vin="WVWZZZ1JZXW000777", nr="B1", data="2026-06-10")
    _login(client, "fe@test.com")

    resp = client.get("/_fragments/submissions?status=needs_data")
    assert resp.status_code == 200
    assert "Nimic pe filtrul curent" in resp.text
    assert "sterge filtrele" in resp.text
