from datetime import datetime
from bson import ObjectId
from fastapi import HTTPException
from app.v1.models.routes import RouteCreate, RouteUpdate
from app.v1.libraries.object import str_to_objectid

COLLECTION_NAME = "routes"

def create_route_service(route: RouteCreate, db) -> dict:
    route_data = route.dict()
    route_data["created_date"] = datetime.utcnow()
    result = db[COLLECTION_NAME].insert_one(route_data)
    route_data["route_id"] = str(result.inserted_id)
    route_data["_id"] = route_data["route_id"]
    return route_data

def get_route_service(route_id: str, db) -> dict:
    route = db[COLLECTION_NAME].find_one({"_id": str_to_objectid(route_id)})
    if not route:
        raise HTTPException(status_code=404, detail="Route not found")
    route["route_id"] = str(route["_id"])
    return route

def get_routes_service(skip: int, limit: int, account_id: Optional[str], db) -> dict:
    query = {}
    if account_id:
        query["account_id"] = account_id
    cursor = db[COLLECTION_NAME].find(query).skip(skip).limit(limit)
    routes = []
    for route in cursor:
        route["route_id"] = str(route["_id"])
        routes.append(route)
    total = db[COLLECTION_NAME].count_documents(query)
    return {"total_count": total, "routes": routes}

def update_route_service(route_id: str, update: RouteUpdate, db) -> dict:
    update_data = update.dict()
    result = db[COLLECTION_NAME].update_one({"_id": str_to_objectid(route_id)}, {"$set": update_data})
    if result.matched_count == 0:
        raise HTTPException(status_code=404, detail="Route not found")
    return get_route_service(route_id, db)

def delete_route_service(route_id: str, db) -> dict:
    route = get_route_service(route_id, db)
    db[COLLECTION_NAME].delete_one({"_id": str_to_objectid(route_id)})
    return route
