from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Float
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from database import Base


class Measurement(Base):
    """One BLE reading taken for a patient (weight / glucose / temperature /
    SpO2 ...). Mirrors the mobile app's MedicalReport."""
    __tablename__ = "measurements"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)

    patient_id = Column(
        Integer,
        ForeignKey("patients.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )

    test_type = Column(String(40), nullable=False)   # e.g. "SPO2", "WEIGHT"
    value = Column(String(40), nullable=False)        # primary reading, as shown
    unit = Column(String(20), nullable=True)          # "%", "kg", "mg/dL", "°F"
    pulse = Column(String(20), nullable=True)         # secondary reading (bpm)
    status = Column(String(20), nullable=True)        # "Normal" / "High" / "Low"
    device_name = Column(String(100), nullable=True)  # BLE device it came from

    # location where the reading was taken (from the mobile device's GPS)
    latitude = Column(Float, nullable=True)
    longitude = Column(Float, nullable=True)

    created_at = Column(DateTime(timezone=True), server_default=func.now())

    patient = relationship("Patient", back_populates="measurements")
