from fastapi import HTTPException
from app.v1.models.platform.iotdevices import IotDeviceCreate, IotDeviceUpdate
from app.v1.libraries.object import str_to_objectid
from datetime import datetime
from pymongo import ASCENDING, DESCENDING

COLLECTION_NAME = "iot_devices"


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


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


async def update_iot_device_service(account_id: str, update: IotDeviceUpdate, db):
    update_data = {k: v for k, v in update.dict(exclude_unset=True).items()}
    update_data["last_updated"] = datetime.utcnow()
    await db[COLLECTION_NAME].update_one({"_id": str_to_objectid(account_id)}, {"$set": update_data})
    return await get_iot_device_service(account_id, db)


async def delete_iot_device_service(account_id: str, db):
    device = await get_iot_device_service(account_id, db)
    await db[COLLECTION_NAME].delete_one({"_id": str_to_objectid(account_id)})
    return device


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