"""S3 / X7 follow-up: the description editor preview is rendered by the server (Markdown + nh3), never by marked.parse() + innerHTML."""
import json
from pathlib import Path

import pytest

from tests.investmentmanager.conftest import CRM_ANN
from tests.investmentmanager.js_dom_harness import IMG, raw_html, run_js

pytestmark = pytest.mark.crm_session_guard
URL = '/crm/offers/description/preview'


def test_preview_returns_sanitized_html_and_keeps_formatting(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    text = f'# Dom\n\nPiękny **dom** w *Łodzi*.\n\n* pokój\n* kuchnia\n\n{IMG}\n\n<script>window.__xss=1</script>[x](javascript:window.__xss=1) [ok](https://example.test)'
    response = ann.post(URL, json={'markdown': text})
    assert response.status_code == 200
    html = response.get_json()['html']
    assert '<h1>Dom</h1>' in html and '<strong>dom</strong>' in html and '<em>Łodzi</em>' in html and '<li>pokój</li>' in html
    assert 'href="https://example.test"' in html
    for needle in ('onerror', '<script', 'javascript:'):
        assert needle not in html


def test_preview_validates_input_and_requires_a_session(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    assert ann.post(URL, json={}).status_code == 400
    assert ann.post(URL, json={'markdown': 5}).status_code == 400
    assert ann.post(URL, data='not json', content_type='text/plain').status_code == 400
    assert ann.post(URL, json={'markdown': 'x' * 200_001}).status_code == 413
    assert ann.post(URL, json={'markdown': ''}).get_json() == {'html': ''}
    anonymous = app.test_client()
    assert anonymous.post(URL, json={'markdown': 'x'}, headers={'Accept': 'application/json'}).status_code == 403


def test_preview_is_protected_by_the_csrf_guard(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    ann.browser_headers = False
    assert ann.post(URL, json={'markdown': 'x'}, headers={'Origin': 'https://evil.example', 'Sec-Fetch-Site': 'cross-site'}).status_code == 403


def test_editor_script_renders_the_server_html_and_no_longer_uses_marked(tmp_path):
    source = (Path(__file__).resolve().parents[2] / 'InvestmentManager' / 'static' / 'js' / 'offers_edit.js').read_text(encoding='utf-8')
    code = '\n'.join(line for line in source.splitlines() if not line.strip().startswith(('*', '/*', '//')))
    assert 'marked.parse(' not in code and 'typeof marked' not in code
    result = run_js(tmp_path, ['offers_edit.js'], f"await renderDescriptionPreview({json.dumps(IMG)}); return 1;",
                    fetch={'/crm/offers/description/preview': {'html': '<p>bezpieczny <strong>podgląd</strong></p>'}})
    assert '<p>bezpieczny <strong>podgląd</strong></p>' in raw_html(result)     # exactly what the server returned (already sanitized)
    assert IMG not in raw_html(result)                                          # the editor text itself is never written as HTML


def test_editor_script_shows_a_text_error_when_the_preview_fails(tmp_path):
    result = run_js(tmp_path, ['offers_edit.js'], "await renderDescriptionPreview('x'); return 1;", fetch={'/crm/offers/description/preview': {'error': 'boom'}})
    assert 'boom' not in raw_html(result)
