from typing import Optional from fastapi import APIRouter, Depends, Query from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.auth import get_current_admin_user from app.database import get_session from app.models import CommunityHighlight from app.schemas import CommunityHighlightCreate, CommunityHighlightUpdate, CommunityHighlightResponse from app.user_models import User router = APIRouter() @router.get("", response_model=list[CommunityHighlightResponse]) async def list_community_highlights( active: Optional[bool] = Query(None, description="Filter by active status"), session: AsyncSession = Depends(get_session), ): query = select(CommunityHighlight).order_by(CommunityHighlight.display_order) if active is not None: query = query.where(CommunityHighlight.active == active) result = await session.execute(query) return list(result.scalars().all()) @router.get("/{highlight_id}", response_model=CommunityHighlightResponse) async def get_community_highlight(highlight_id: int, session: AsyncSession = Depends(get_session)): result = await session.execute(select(CommunityHighlight).where(CommunityHighlight.id == highlight_id)) highlight = result.scalar_one_or_none() if not highlight: return {"error": "Community highlight not found"} return highlight @router.post("", response_model=CommunityHighlightResponse, status_code=201) async def create_community_highlight( payload: CommunityHighlightCreate, session: AsyncSession = Depends(get_session), _: User = Depends(get_current_admin_user), ): highlight = CommunityHighlight(**payload.model_dump(), active=True) session.add(highlight) await session.commit() await session.refresh(highlight) return highlight @router.put("/{highlight_id}", response_model=CommunityHighlightResponse) async def update_community_highlight( highlight_id: int, payload: CommunityHighlightUpdate, session: AsyncSession = Depends(get_session), _: User = Depends(get_current_admin_user), ): result = await session.execute(select(CommunityHighlight).where(CommunityHighlight.id == highlight_id)) highlight = result.scalar_one_or_none() if not highlight: return {"error": "Community highlight not found"} for key, value in payload.model_dump(exclude_unset=True).items(): setattr(highlight, key, value) await session.commit() await session.refresh(highlight) return highlight @router.delete("/{highlight_id}", status_code=204) async def delete_community_highlight( highlight_id: int, session: AsyncSession = Depends(get_session), _: User = Depends(get_current_admin_user), ): result = await session.execute(select(CommunityHighlight).where(CommunityHighlight.id == highlight_id)) highlight = result.scalar_one_or_none() if not highlight: return {"error": "Community highlight not found"} await session.delete(highlight) await session.commit()