import uuid

from sqlalchemy import Column, DateTime, Float, ForeignKey, Index, Integer
from sqlalchemy.dialects.postgresql import UUID

from shared.database import BaseModel


class UserLocation(BaseModel):
    __tablename__ = "user_locations"

    uuid = Column(UUID(as_uuid=True), default=uuid.uuid4, unique=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)

    latitude = Column(Float, nullable=False)
    longitude = Column(Float, nullable=False)
    accuracy = Column(Float)  # GPS accuracy in meters
    altitude = Column(Float)
    speed = Column(Float)  # Speed in m/s
    heading = Column(Float)  # Direction in degrees

    # Indexes for geospatial queries
    __table_args__ = (
        Index("idx_location_coords", "latitude", "longitude"),
        Index("idx_location_user_time", "user_id", "created_at"),
    )

    def __repr__(self):
        return f"<UserLocation user_id={self.user_id} lat={self.latitude} lng={self.longitude}>"


class LocationHistory(BaseModel):
    __tablename__ = "location_history"

    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
    latitude = Column(Float, nullable=False)
    longitude = Column(Float, nullable=False)
    accuracy = Column(Float)
    recorded_at = Column(DateTime(timezone=True), nullable=False)

    # Partition by date for better performance
    __table_args__ = (
        Index("idx_history_user_date", "user_id", "recorded_at"),
        Index("idx_history_coords_date", "latitude", "longitude", "recorded_at"),
    )

    def __repr__(self):
        return f"<LocationHistory user_id={self.user_id} at={self.recorded_at}>"
