from fastapi import HTTPException
from app.v1.models.platform.geofencerules import GeofenceRuleCreate, GeofenceRuleUpdate
from app.v1.libraries.object import str_to_objectid
from datetime import datetime
from typing import Optional, Dict, Any
from pymongo import ASCENDING, DESCENDING

COLLECTION_NAME = "geofence_rules"

async def create_geofence_rule_service(rule: GeofenceRuleCreate, db):
    data = rule.dict()
    data["created_date"] = datetime.utcnow()
    result = db[COLLECTION_NAME].insert_one(data)
    data["id"] = str(result.inserted_id)
    return data

async def get_geofence_rule_service(account_id: str, db):
    rule = db[COLLECTION_NAME].find_one({"_id": str_to_objectid(account_id)})
    if not rule:
        raise HTTPException(status_code=404, detail="Geofence rule not found")
    rule["id"] = str(rule["_id"])
    return rule

async def update_geofence_rule_service(account_id: str, update: GeofenceRuleUpdate, db):
    update_dict = {k: v for k, v in update.dict(exclude_unset=True).items()}
    db[COLLECTION_NAME].update_one({"_id": str_to_objectid(account_id)}, {"$set": update_dict})
    return await get_geofence_rule_service(account_id, db)

async def delete_geofence_rule_service(account_id: str, db):
    rule = await get_geofence_rule_service(account_id, db)
    db[COLLECTION_NAME].delete_one({"_id": str_to_objectid(account_id)})
    return rule

async def list_geofence_rules_service(skip: int, limit: int, db):
    cursor = db[COLLECTION_NAME].find().skip(skip).limit(limit)
    rules = []
    for rule in cursor:
        rule["id"] = str(rule["_id"])
        rules.append(rule)
    total = db[COLLECTION_NAME].count_documents({})
    return {"total_count": total, "users": rules}
