from fastapi import HTTPException

from ..database import db
from ..models.image import Image
from bson import ObjectId

from ..schemas.image import ImageUpdate, DepthProcessingRequest


async def create_image(img: DepthProcessingRequest):
    collection = db.image
    image = {
        "url": str(img.input_url)
    }

    result = await collection.insert_one(image)
    created_image = await collection.find_one({"_id": result.inserted_id})
    return created_image


async def patch_image(
    id: str,
    update_data: ImageUpdate
):
    update_dict = update_data.model_dump(exclude_unset=True)
    if not update_dict:
        raise HTTPException(status_code=400, detail="No fields to update")
    result = await db.image.update_one(
        {"_id": ObjectId(id)},
        {"$set": update_dict}
    )
    if result.modified_count == 0:
        raise HTTPException(status_code=404, detail="Image not found")

    return await db.image.find_one({"_id": ObjectId(id)})


async def get_image(image_id: str):
    image = await db.image.find_one({"_id": ObjectId(image_id)})
    if image:
        return ImageUpdate(**image)
    return None


async def get_all_images():
    cursor = db.image.find()
    images = await cursor.to_list(length=100)  # Limit to 100 for this example
    return [ImageUpdate(**image) for image in images]