from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from backend.app.api.deps import get_current_user, get_db
from backend.app.models import StationCreate, StationModel, StationUpdate, UserPublic
from backend.app.services.stations import (
    archive_station,
    create_station,
    get_station,
    list_stations,
    update_station,
)

router = APIRouter(prefix="/stations", tags=["stations"])


@router.get("", response_model=list[StationModel])
def read_stations(
    include_inactive: bool = False,
    _: UserPublic = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> list[StationModel]:
    return list_stations(db, include_inactive=include_inactive)


@router.get("/{station_id}", response_model=StationModel)
def read_station(
    station_id: str,
    _: UserPublic = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> StationModel:
    try:
        return get_station(db, station_id)
    except LookupError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
        ) from exc
    except ValueError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc


@router.post("", response_model=StationModel, status_code=status.HTTP_201_CREATED)
def create_station_endpoint(
    payload: StationCreate,
    _: UserPublic = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> StationModel:
    try:
        return create_station(db, payload)
    except ValueError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc


@router.put("/{station_id}", response_model=StationModel)
def update_station_endpoint(
    station_id: str,
    payload: StationUpdate,
    _: UserPublic = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> StationModel:
    try:
        return update_station(db, station_id, payload)
    except LookupError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
        ) from exc
    except ValueError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc


@router.post("/{station_id}/archive", response_model=StationModel)
def archive_station_endpoint(
    station_id: str,
    _: UserPublic = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> StationModel:
    try:
        return archive_station(db, station_id)
    except LookupError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)
        ) from exc
    except ValueError as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
        ) from exc
