"""News APIs."""

from typing import List

from fastapi import (
    APIRouter,
    HTTPException,
    Request,
)

from app.api.v1.auth import get_current_user
from app.core.config import settings
from app.core.limiter import limiter
from app.core.logging import logger
from app.schemas.news import NewsResponse
from app.services.database import DatabaseService
from app.utils.sanitization import sanitize_string

router = APIRouter()
db_service = DatabaseService()


@router.get("/all", response_model=List[NewsResponse])
# @limiter.limit(settings.RATE_LIMIT_ENDPOINTS["messages"][0])
async def get_news(
    request: Request,
):
    """Get all news.

    Args:
        request: The FastAPI request object for rate limiting.

    Returns:
        List[NewsResponse]: List of news.

    Raises:
        HTTPException: If there's an error retrieving the news.
    """
    try:
        news = await db_service.get_news()
        return [
            NewsResponse(
                id=sanitize_string(news_item.id),
                title=sanitize_string(news_item.title),
                category=sanitize_string(news_item.category),
                abstract=sanitize_string(news_item.abstract),
                body=sanitize_string(news_item.body),
                time=sanitize_string(news_item.time),
                converted_time=sanitize_string(news_item.converted_time),
            )
            for news_item in news
        ]
    except ValueError as ve:
        logger.error("get_news_validation_failed", error=str(ve), exc_info=True)
        raise HTTPException(status_code=422, detail=str(ve))
