"""Teste US-006 (PRD 3.5): listare + editare/stergere formate de coloane salvate.

Scoped pe cont (fara leak cross-account). Coloanele afisate = cheile json_mapare.
"""

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 _csrf(client) -> str:
    resp = client.get("/?tab=mapari")
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text) or \
        re.search(r'value="([^"]+)"\s+name="csrf_token"', resp.text)
    assert m
    return m.group(1)


def _seed_format(acct: int, sig: str, mapare: dict, fmt: str | None) -> int:
    from app.db import get_connection
    conn = get_connection()
    try:
        cur = conn.execute(
            "INSERT INTO column_mappings (account_id, signature_coloane, json_mapare, format_data) "
            "VALUES (?, ?, ?, ?)",
            (acct, sig, json.dumps(mapare, ensure_ascii=False), fmt),
        )
        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, "formate.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_lista_formate_coloane(client):
    """Listarea intoarce formatele contului cu coloane + format_data."""
    acct = _create_account_user("lf@test.com")
    _seed_format(acct, "sig-1", {"Serie sasiu": "vin", "Nr auto": "nr_inmatriculare"}, "DD.MM.YYYY")

    from app.db import get_connection
    from app.web.routes import _load_column_formats
    conn = get_connection()
    try:
        rows = _load_column_formats(conn, acct)
    finally:
        conn.close()

    assert len(rows) == 1
    assert rows[0]["format_data"] == "DD.MM.YYYY"
    assert "Serie sasiu" in rows[0]["columns"]
    assert rows[0]["mappings"]["Serie sasiu"] == "vin"


def test_editeaza_format_coloane(client):
    """POST schimba format_data pentru un format, scoped pe cont."""
    acct = _create_account_user("ef@test.com")
    fid = _seed_format(acct, "sig-2", {"Data": "data_prestatie"}, "DD.MM.YYYY")

    _login(client, "ef@test.com")
    csrf = _csrf(client)
    resp = client.post("/formate-coloane/editeaza", data={
        "format_id": str(fid), "format_data": "YYYY-MM-DD", "csrf_token": csrf,
    })
    assert resp.status_code == 200

    from app.db import get_connection
    conn = get_connection()
    try:
        row = conn.execute("SELECT format_data FROM column_mappings WHERE id=?", (fid,)).fetchone()
    finally:
        conn.close()
    assert row["format_data"] == "YYYY-MM-DD"


def test_sterge_format_coloane_scoped(client):
    """DELETE scoped pe cont: formatul altui cont ramane neatins (id strain ignorat)."""
    acct1 = _create_account_user("sf1@test.com", name="C1")
    acct2 = _create_account_user("sf2@test.com", name="C2")
    fid1 = _seed_format(acct1, "sig-a", {"A": "vin"}, None)
    fid2 = _seed_format(acct2, "sig-b", {"B": "vin"}, None)

    _login(client, "sf1@test.com")
    csrf = _csrf(client)

    # Incearca sa stearga formatul altui cont -> ignorat (scoped pe id+account)
    resp = client.post("/formate-coloane/sterge", data={"format_id": str(fid2), "csrf_token": csrf})
    assert resp.status_code == 200

    # Sterge formatul propriu -> ok
    resp = client.post("/formate-coloane/sterge", data={"format_id": str(fid1), "csrf_token": csrf})
    assert resp.status_code == 200

    from app.db import get_connection
    conn = get_connection()
    try:
        r1 = conn.execute("SELECT 1 FROM column_mappings WHERE id=?", (fid1,)).fetchone()
        r2 = conn.execute("SELECT 1 FROM column_mappings WHERE id=?", (fid2,)).fetchone()
    finally:
        conn.close()
    assert r1 is None, "formatul propriu trebuia sters"
    assert r2 is not None, "formatul altui cont NU trebuia sters (leak)"
