"""Radiology Image repository for database operations on imaging data."""
from typing import List, Optional

from bson import ObjectId

from app.db import Database
from app.models.radiology_image import RadiologyImage

COL = "radiology_images"

def create(image: RadiologyImage) -> RadiologyImage:
    """Create a new radiology image record in the database."""
    image_to_insert = image.to_bson()
    res = Database.get_db().get_collection(COL).insert_one(image_to_insert)
    return RadiologyImage.from_bson({**image_to_insert, "_id": res.inserted_id})

def find_by_id(image_id: str) -> Optional[RadiologyImage]:
    """Find a radiology image record by its ID."""
    if not ObjectId.is_valid(image_id):
        return None
    doc = Database.get_db().get_collection(COL).find_one({"_id": ObjectId(image_id)})
    return RadiologyImage.from_bson(doc) if doc else None

def find_by_patient_id(patient_id: str) -> List[RadiologyImage]:
    """Find all radiology image records for a patient."""
    if not ObjectId.is_valid(patient_id):
        return []
    docs = Database.get_db().get_collection(COL).find({"patientId": ObjectId(patient_id)})
    return [RadiologyImage.from_bson(doc) for doc in docs]
