from sqlalchemy import insert, select, update, delete from fastapi import HTTPException from models.db import points_of_interest_table from models.schemas import PointOfInterest from sqlalchemy.ext.asyncio import AsyncSession class PointsOfInterestService: @staticmethod async def create_point_of_interest(point: PointOfInterest, db: AsyncSession): query = insert(points_of_interest_table).values( label=point.label, description=point.description, icon=point.icon, organization=point.organization, gps_coordinates=point.gps_coordinates, added_by=point.added_by, ) try: result = await db.execute(query) await db.commit() point_id = result.inserted_primary_key[0] return {"id": point_id, **point.dict()} except Exception as e: await db.rollback() raise HTTPException(status_code=500, detail=f"Could not create point of interest: {str(e)}") @staticmethod async def get_point_of_interest(point_id: int, db: AsyncSession): query = select(points_of_interest_table).where(points_of_interest_table.c.id == point_id) result = await db.execute(query) point = result.fetchone() if not point: raise HTTPException(status_code=404, detail="Point of interest not found") return dict(point) @staticmethod async def get_all_points_of_interest(db: AsyncSession): query = select(points_of_interest_table) result = await db.execute(query) return [dict(row) for row in result.fetchall()] @staticmethod async def update_point_of_interest(point_id: int, data: dict, db: AsyncSession): query = ( update(points_of_interest_table) .where(points_of_interest_table.c.id == point_id) .values(**data) ) try: result = await db.execute(query) if result.rowcount == 0: raise HTTPException(status_code=404, detail="Point of interest not found") await db.commit() return {"message": "Point of interest updated successfully"} except Exception as e: await db.rollback() raise HTTPException(status_code=500, detail=f"Could not update point of interest: {str(e)}") @staticmethod async def delete_point_of_interest(point_id: int, db: AsyncSession): query = delete(points_of_interest_table).where(points_of_interest_table.c.id == point_id) try: result = await db.execute(query) if result.rowcount == 0: raise HTTPException(status_code=404, detail="Point of interest not found") await db.commit() return {"message": "Point of interest deleted successfully"} except Exception as e: await db.rollback() raise HTTPException(status_code=500, detail=f"Could not delete point of interest: {str(e)}")