"""Security middleware tests: headers, auth gate, fail-closed production config."""
import os

import pytest
from fastapi.testclient import TestClient

from app.main import app
from app.security import enforce_production_safety

client = TestClient(app)


def test_security_headers_present():
    r = client.get("/health")
    assert r.headers["X-Content-Type-Options"] == "nosniff"
    assert r.headers["X-Frame-Options"] == "DENY"
    assert r.headers["Referrer-Policy"] == "no-referrer"


def test_auth_gate_blocks_api_when_enabled(monkeypatch):
    monkeypatch.setenv("REQUIRE_AUTH", "true")
    r = client.get("/api/signals")
    assert r.status_code == 401
    r = client.post("/api/scanner/run")
    assert r.status_code == 401
    r = client.request("DELETE", "/api/signals/history")
    assert r.status_code == 401
    # health + auth remain public
    assert client.get("/health").status_code == 200


def test_auth_gate_allows_valid_token(monkeypatch):
    monkeypatch.setenv("REQUIRE_AUTH", "false")
    email = "gate-test@example.com"
    client.post("/api/auth/register", json={"email": email, "password": "secret123"})
    token = client.post(
        "/api/auth/login", data={"username": email, "password": "secret123"}
    ).json()["access_token"]

    monkeypatch.setenv("REQUIRE_AUTH", "true")
    r = client.get("/api/signals", headers={"Authorization": f"Bearer {token}"})
    assert r.status_code == 200
    r = client.get("/api/signals", headers={"Authorization": "Bearer garbage"})
    assert r.status_code == 401


def test_production_refuses_weak_secret(monkeypatch):
    monkeypatch.setenv("ENV", "production")
    monkeypatch.setattr("app.security.settings.SECRET_KEY", "dev-secret-change-me")
    with pytest.raises(RuntimeError, match="SECRET_KEY"):
        enforce_production_safety()


def test_production_requires_auth(monkeypatch):
    monkeypatch.setenv("ENV", "production")
    monkeypatch.setenv("REQUIRE_AUTH", "false")
    monkeypatch.setattr("app.security.settings.SECRET_KEY", "x" * 48)
    with pytest.raises(RuntimeError, match="REQUIRE_AUTH"):
        enforce_production_safety()


def test_development_boots_freely(monkeypatch):
    monkeypatch.setenv("ENV", "development")
    enforce_production_safety()  # no exception
