"""Bus stops API endpoints."""
from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session, select
from typing import List
from uuid import UUID

from app.core.database import get_session
from app.models.bus_stop import BusStop
from app.schemas.bus_stop import BusStopResponse, BusStopCreate, BusStopUpdate
from app.api.deps import get_current_admin

router = APIRouter(prefix="/api/bus-stops", tags=["bus-stops"])


@router.get("", response_model=List[BusStopResponse])
async def get_bus_stops(session: Session = Depends(get_session)):
    """Get all bus stops."""
    statement = select(BusStop)
    stops = session.exec(statement).all()
    return stops


@router.get("/{stop_id}", response_model=BusStopResponse)
async def get_bus_stop(stop_id: UUID, session: Session = Depends(get_session)):
    """Get a single bus stop by ID."""
    stop = session.get(BusStop, stop_id)
    if not stop:
        raise HTTPException(status_code=404, detail="Bus stop not found")
    return stop


@router.get("/{stop_id}/routes")
async def get_bus_stop_routes(stop_id: UUID, session: Session = Depends(get_session)):
    """Get all routes passing through a bus stop."""
    from app.models.route_stop import RouteStop
    from app.models.route import Route
    
    statement = select(Route).join(
        RouteStop, RouteStop.route_id == Route.id
    ).where(RouteStop.stop_id == stop_id)
    
    routes = session.exec(statement).all()
    return routes

@router.post("", response_model=BusStopResponse)
async def create_bus_stop(
    bus_stop: BusStopCreate,
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """Create a new bus stop (Admin only)."""
    db_stop = BusStop.model_validate(bus_stop)
    session.add(db_stop)
    session.commit()
    session.refresh(db_stop)
    return db_stop

@router.put("/{stop_id}", response_model=BusStopResponse)
async def update_bus_stop(
    stop_id: UUID,
    stop_update: BusStopUpdate,
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """Update a bus stop (Admin only)."""
    db_stop = session.get(BusStop, stop_id)
    if not db_stop:
        raise HTTPException(status_code=404, detail="Bus stop not found")
    
    stop_data = stop_update.model_dump(exclude_unset=True)
    for key, value in stop_data.items():
        setattr(db_stop, key, value)
        
    session.add(db_stop)
    session.commit()
    session.refresh(db_stop)
    return db_stop

@router.delete("/{stop_id}")
async def delete_bus_stop(
    stop_id: UUID,
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """Delete a bus stop (Admin only)."""
    db_stop = session.get(BusStop, stop_id)
    if not db_stop:
        raise HTTPException(status_code=404, detail="Bus stop not found")
        
    session.delete(db_stop)
    session.commit()
    return {"ok": True}
