"""This module handles CRUD operations for users in the database, based on pydanctic schemas."""

from datetime import datetime

from sqlalchemy.orm import Session

from backend.models import devices as devicemodel
from backend.models import users as usermodel
from backend.schemas import devices as deviceschema
from backend.exceptions import DataIntegrityException, NotFoundException


def create_device(db: Session, device: deviceschema.DeviceCreate) -> deviceschema.Device:
    """Creates the specified device in the database."""

    db_user = db.query(usermodel.User).filter(usermodel.User.id == device.owner_id).first()
    if not db_user:
        raise NotFoundException("Attempted to create a device for a nonexistent user.")
    if not db_user.patient:
        raise DataIntegrityException("Attempted to create a device for a user who is not a patient.")

    db_device = devicemodel.Device(
        model_id=device.model_id,
        owner_id=device.owner_id,
    )
    db.add(db_device)
    db.commit()
    db.refresh(db_device)

    return deviceschema.Device.from_orm(db_device)


def read_device(db: Session, id: int) -> deviceschema.Device | None:
    """Queries the db for a device with the specified id and returns it."""

    db_device = db.query(devicemodel.Device).filter(devicemodel.Device.id == id).first()
    if not db_device:
        raise NotFoundException(f"Device with id '{id}' was not found.")

    return deviceschema.Device.from_orm(db_device)


def update_device(db: Session, device: deviceschema.DeviceUpdate, id: int) -> deviceschema.Device:
    """Updates the specified device's last seen time."""

    db_device = db.query(devicemodel.Device).filter(devicemodel.Device.id == id).first()
    if not db_device:
        raise NotFoundException(f"Device with id '{id}' was not found.")

    db_device.last_seen = device.last_seen
    db.commit()
    db.refresh(db_device)

    return deviceschema.Device.from_orm(db_device)


def delete_device(db: Session, id: int) -> deviceschema.Device:
    """Deletes the user with the provided id from the db."""

    db_device = db.query(devicemodel.Device).filter(devicemodel.Device.id == id).first()
    if not db_device:
        raise NotFoundException(f"Device with id '{id}' was not found.")
    device_copy = deviceschema.Device.from_orm(db_device)

    db.delete(db_device)
    db.commit()

    return device_copy
