"""Teste P1-4 (hardening 2026-07-03): security headers pe TOATE raspunsurile."""

from __future__ import annotations

import os
import tempfile

import pytest
from fastapi.testclient import TestClient


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "sh.db"))
    monkeypatch.setenv("AUTOPASS_LOG_DIR", os.path.join(tmp, "logs"))
    from app.config import get_settings
    get_settings.cache_clear()
    from app.main import app
    with TestClient(app) as c:
        yield c
    get_settings.cache_clear()


def _assert_common_headers(headers) -> None:
    assert headers.get("X-Content-Type-Options") == "nosniff"
    assert headers.get("X-Frame-Options") == "DENY"
    assert headers.get("Referrer-Policy") == "strict-origin-when-cross-origin"


def test_headere_pe_raspuns_200(client):
    r = client.get("/healthz")
    assert r.status_code == 200
    _assert_common_headers(r.headers)


def test_headere_pe_raspuns_404(client):
    r = client.get("/o/ruta/care/nu/exista")
    assert r.status_code == 404
    _assert_common_headers(r.headers)


def test_hsts_absent_pe_http(client):
    r = client.get("/healthz")
    assert "Strict-Transport-Security" not in r.headers


def test_hsts_prezent_pe_https():
    tmp = tempfile.mkdtemp()
    import os as _os

    _os.environ["AUTOPASS_DB_PATH"] = _os.path.join(tmp, "sh_https.db")
    from app.config import get_settings
    get_settings.cache_clear()
    from app.main import app

    with TestClient(app, base_url="https://testserver") as c:
        r = c.get("/healthz")
        assert r.status_code == 200
        assert r.headers.get("Strict-Transport-Security") == (
            "max-age=31536000; includeSubDomains"
        )
    get_settings.cache_clear()
    _os.environ.pop("AUTOPASS_DB_PATH", None)
