"""Defines the endpoint for fetching toilet locations."""
from fastapi import HTTPException, APIRouter, Query

from ..structs.toilets import Toilets
from .toilets_manager import ToiletsManager


# Define the API router
router = APIRouter()


@router.post("/toilets/new")
def get_toilets(location: tuple[float, float] = Query(...), radius: int = 500) -> list[Toilets] :
    """
    Endpoint to find toilets within a specified radius from a given location.

    This endpoint expects the `location` and `radius` as **query parameters**, not in the request body.

    Args:
        location (tuple[float, float]): The latitude and longitude of the location to search from.
        radius (int, optional): The radius (in meters) within which to search for toilets. Defaults to 500 meters.

    Returns:
        list[Toilets]: A list of Toilets objects that meet the criteria.
    """
    if location is None:
        raise HTTPException(status_code=406, detail="Coordinates not provided or invalid")
    if not (-90 <= location[0] <= 90 or -180 <= location[1] <= 180):
        raise HTTPException(status_code=422, detail="Start coordinates not in range")

    toilets_manager = ToiletsManager(location, radius)

    try :
        toilets_list = toilets_manager.generate_toilet_list()
    except KeyError as exc:
        raise HTTPException(status_code=404, detail="No toilets found") from exc

    return toilets_list
