from typing import List

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

from app.core.usecases.auth_service import verify_token
from app.infrastructure.database.dependencies import get_db
from app.core.entities.city import CityEntity
from app.core.usecases.city_service import CitiesService
from app.infrastructure.database.models.users import User

router = APIRouter()


@router.get("/cities", response_model=List[CityEntity])
def read_cities(db: Session = Depends(get_db),
                current_user: User = Depends(verify_token)):
    service = CitiesService(db)
    return service.get_all_cities()


@router.get("/cities/{city_id}", response_model=CityEntity)
def read_city(city_id: int, db: Session = Depends(get_db),
              current_user: User = Depends(verify_token)):
    service = CitiesService(db)
    city = service.get_city_by_id(city_id)
    if city is None:
        raise HTTPException(status_code=404, detail="City not found")
    return city


@router.post("/cities", response_model=CityEntity)
def create_city(city: CityEntity, db: Session = Depends(get_db),
                current_user: User = Depends(verify_token)):
    service = CitiesService(db)
    return service.create_city(city)


@router.put("/cities/{city_id}", response_model=CityEntity)
def update_city(city_id: int, city: CityEntity, db: Session = Depends(get_db),
                current_user: User = Depends(verify_token)):
    service = CitiesService(db)
    updated_city = service.update_city(city_id, city)
    if updated_city is None:
        raise HTTPException(status_code=404, detail="City not found")
    return updated_city


@router.delete("/cities/{city_id}", response_model=bool)
def delete_city(city_id: int, db: Session = Depends(get_db),
                current_user: User = Depends(verify_token)):
    service = CitiesService(db)
    success = service.delete_city(city_id)
    if not success:
        raise HTTPException(status_code=404, detail="City not found")
    return success
