"""Tests for app.core.error_handlers — global exception handler and security headers"""

import pytest
from unittest.mock import AsyncMock, MagicMock


@pytest.mark.asyncio
async def test_global_exception_handler():
    from app.core.error_handlers import global_exception_handler
    from fastapi import Request

    request = MagicMock(spec=Request)
    exc = ValueError("test error")
    response = await global_exception_handler(request, exc)
    assert response.status_code == 500
    assert b"INTERNAL_ERROR" in response.body


@pytest.mark.asyncio
async def test_http_exception_handler():
    from app.core.error_handlers import http_exception_handler
    from fastapi import HTTPException, Request

    request = MagicMock(spec=Request)
    exc = HTTPException(status_code=403, detail="Forbidden")
    response = await http_exception_handler(request, exc)
    assert response.status_code == 403
    assert b"Forbidden" in response.body


@pytest.mark.asyncio
async def test_http_exception_handler_404():
    from app.core.error_handlers import http_exception_handler
    from fastapi import HTTPException, Request

    request = MagicMock(spec=Request)
    exc = HTTPException(status_code=404, detail="Not found")
    response = await http_exception_handler(request, exc)
    assert response.status_code == 404
    assert b"Not found" in response.body


@pytest.mark.asyncio
async def test_security_headers_middleware():
    from app.core.error_handlers import SecurityHeadersMiddleware
    from fastapi import Request
    from fastapi.responses import JSONResponse

    mock_request = MagicMock(spec=Request)
    mock_call_next = AsyncMock(return_value=JSONResponse(content={}))

    mw = SecurityHeadersMiddleware(object())
    response = await mw.dispatch(mock_request, mock_call_next)

    assert response.headers["X-Content-Type-Options"] == "nosniff"
    assert response.headers["X-Frame-Options"] == "DENY"
    assert response.headers["X-XSS-Protection"] == "1; mode=block"
    assert response.headers["Referrer-Policy"] == "strict-origin-when-cross-origin"
    assert "Content-Security-Policy" in response.headers
    assert "default-src 'self'" in response.headers["Content-Security-Policy"]
    assert "Permissions-Policy" in response.headers
