"""Public read API for articles. No authentication required — these endpoints power the site front end: * ``GET /api/v1/articles`` — the home page feed. Returns *published* articles newest-first, each with its author and category embedded. * ``GET /api/v1/articles/{id}`` — a single published article (404 when missing or still a draft). Drafts (``published=False``) are never exposed here; admins manage them via the admin area (``api.v1.admin``). """ from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session, joinedload from db.session import get_db from models import Article from schemas import ArticleRead router = APIRouter(prefix="/articles", tags=["articles"]) def _load_published_article(db: Session, article_id: int) -> Article: article = ( db.query(Article) .options(joinedload(Article.author), joinedload(Article.category)) .filter(Article.id == article_id, Article.published.is_(True)) .first() ) if article is None: raise HTTPException(status_code=404, detail="Article not found") return article @router.get("", response_model=list[ArticleRead], summary="List published articles") def list_published_articles( db: Session = Depends(get_db), ) -> list[Article]: """Published articles, newest first, with author and category embedded.""" return ( db.query(Article) .options(joinedload(Article.author), joinedload(Article.category)) .filter(Article.published.is_(True)) .order_by(Article.created_at.desc()) .all() ) @router.get("/{article_id}", response_model=ArticleRead, summary="Get a published article") def get_published_article( article_id: int, db: Session = Depends(get_db), ) -> Article: return _load_published_article(db, article_id)