"""S3 / X8: uploaded offer documents are served inline only for the types the panel previews; active/opaque types are downloads.

No upload restrictions were added (decision): everything can still be uploaded, listed, downloaded and deleted.
"""
import io

import pytest

from tests.investmentmanager.conftest import CRM_ANN, CRM_BOB, CRM_MASTER

pytestmark = pytest.mark.crm_session_guard
OFFER = 501                       # owned by CRM_ANN in crm_env
ACTIVE = b'<html><img src=x onerror=window.__xss=1><script>window.__xss=1</script></html>'


def _upload(client, name, content):
    response = client.post(f'/crm/offers/documents/{OFFER}', data={'file': (io.BytesIO(content), name)}, content_type='multipart/form-data')
    assert response.status_code == 200 and response.get_json()['success'] is True, response.get_data(as_text=True)


def _get(client, name):
    from urllib.parse import quote
    return client.get(f'/crm/offers/documents/{OFFER}/file/{quote(name)}')


@pytest.mark.parametrize('name', ['umowa.html', 'UMOWA.HTM', 'plan.svg', 'dane.xml', 'skrypt.js', 'strona.xhtml', 'plik.docx', 'arkusz.xlsx', 'bez_rozszerzenia',
                                  'podwojne.pdf.html', 'trailing.html.', 'archiwum.zip'])
def test_active_and_opaque_documents_are_downloads_with_protective_headers(app, crm_env, crm_login, name):
    ann = crm_login(app, CRM_ANN)
    _upload(ann, name, ACTIVE)
    response = _get(ann, name)
    assert response.status_code == 200 and response.get_data() == ACTIVE                       # the content itself is untouched
    assert response.headers['Content-Disposition'].startswith('attachment')
    assert response.headers['X-Content-Type-Options'] == 'nosniff'
    assert response.headers['Content-Security-Policy'] == "default-src 'none'; sandbox"


@pytest.mark.parametrize('name', ['notatki.txt', 'wyceny.csv', 'config.json', 'NOTATKI.TXT'])
def test_text_previews_stay_inline_but_are_always_plain_text(app, crm_env, crm_login, name):
    ann = crm_login(app, CRM_ANN)
    _upload(ann, name, ACTIVE)
    response = _get(ann, name)
    assert response.status_code == 200 and response.get_data() == ACTIVE
    assert 'attachment' not in response.headers.get('Content-Disposition', '')
    assert response.headers['Content-Type'].startswith('text/plain') and 'charset=utf-8' in response.headers['Content-Type']
    assert response.headers['X-Content-Type-Options'] == 'nosniff' and 'sandbox' in response.headers['Content-Security-Policy']


@pytest.mark.parametrize('name,mimetype', [('zdjęcie.jpg', 'image/jpeg'), ('plan.PNG', 'image/png'), ('a.gif', 'image/gif'), ('b.webp', 'image/webp'), ('c.jpeg', 'image/jpeg')])
def test_image_previews_stay_inline(app, crm_env, crm_login, name, mimetype):
    ann = crm_login(app, CRM_ANN)
    _upload(ann, name, b'\x89PNG-not-really')
    response = _get(ann, name)
    assert response.status_code == 200 and response.headers['Content-Type'].startswith(mimetype)
    assert 'attachment' not in response.headers.get('Content-Disposition', '')
    assert response.headers['X-Content-Type-Options'] == 'nosniff' and 'sandbox' in response.headers['Content-Security-Policy']


def test_pdf_preview_stays_inline_and_keeps_the_browser_viewer(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    _upload(ann, 'umowa 1&2.pdf', b'%PDF-1.4 test')
    response = _get(ann, 'umowa 1&2.pdf')
    assert response.status_code == 200 and response.headers['Content-Type'].startswith('application/pdf')
    assert 'attachment' not in response.headers.get('Content-Disposition', '') and response.headers['X-Content-Type-Options'] == 'nosniff'
    # no CSP sandbox / object-src 'none' (either would disable the browser PDF viewer used by the iframe preview); only framing is limited\r
    assert response.headers['Content-Security-Policy'] == "frame-ancestors 'self'"


def test_listing_download_delete_and_ownership_are_unchanged(app, crm_env, crm_login):
    ann, bob, master = crm_login(app, CRM_ANN), crm_login(app, CRM_BOB), crm_login(app, CRM_MASTER)
    _upload(ann, 'Umowa ŁÓDŹ.html', ACTIVE)
    assert ann.get(f'/crm/offers/documents/{OFFER}').get_json() == {'documents': ['Umowa ŁÓDŹ.html']}
    assert _get(master, 'Umowa ŁÓDŹ.html').status_code == 200                      # master reaches every offer
    assert _get(bob, 'Umowa ŁÓDŹ.html').status_code == 403                         # S1 ownership untouched
    assert _get(ann, 'nie-ma.pdf').status_code == 404
    assert ann.post(f'/crm/offers/documents/{OFFER}/delete', json={'filename': 'Umowa ŁÓDŹ.html'}).get_json() == {'success': True}
    assert ann.get(f'/crm/offers/documents/{OFFER}').get_json() == {'documents': []}
