# gateway/app/routes/public.py
"""
Public routes for API Gateway - Handles unauthenticated public endpoints
"""

from fastapi import APIRouter, Request
import httpx
import logging

from app.core.config import settings

logger = logging.getLogger(__name__)
router = APIRouter()


async def _proxy_to_notification_service(request: Request, path: str):
    """Proxy request to notification service"""
    try:
        body = await request.body()

        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.request(
                method=request.method,
                url=f"{settings.NOTIFICATION_SERVICE_URL}{path}",
                content=body,
                headers={
                    "Content-Type": request.headers.get("Content-Type", "application/json"),
                }
            )

            return response.json() if response.content else {}

    except httpx.TimeoutException:
        logger.error(f"Timeout proxying to notification service: {path}")
        return {"success": False, "message": "Service temporarily unavailable"}
    except Exception as e:
        logger.error(f"Error proxying to notification service: {e}")
        return {"success": False, "message": "Internal error"}


@router.post("/contact")
async def submit_contact_form(request: Request):
    """Proxy contact form submission to notification service"""
    return await _proxy_to_notification_service(request, "/api/v1/public/contact")


@router.post("/feedback")
async def submit_feedback_form(request: Request):
    """Proxy feedback form submission to notification service"""
    return await _proxy_to_notification_service(request, "/api/v1/public/feedback")


@router.post("/prelaunch-subscribe")
async def submit_prelaunch_email(request: Request):
    """Proxy pre-launch email subscription to notification service"""
    return await _proxy_to_notification_service(request, "/api/v1/public/prelaunch-subscribe")
