import uuid

from sqlalchemy import (
    Boolean,
    Column,
    DateTime,
    Float,
    ForeignKey,
    Integer,
    String,
    Text,
)
from sqlalchemy.dialects.postgresql import UUID

from shared.database import BaseModel


class EmergencyAlert(BaseModel):
    __tablename__ = "emergency_alerts"

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

    # Location at time of alert
    latitude = Column(Float, nullable=False)
    longitude = Column(Float, nullable=False)
    address = Column(String(500))

    # Alert details
    alert_type = Column(String(50), default="general")  # general, medical, violence, etc.
    message = Column(Text)
    is_resolved = Column(Boolean, default=False)
    resolved_at = Column(DateTime(timezone=True))
    resolved_by = Column(Integer, ForeignKey("users.id"))

    # Response tracking
    notified_users_count = Column(Integer, default=0)
    responded_users_count = Column(Integer, default=0)

    def __repr__(self):
        return f"<EmergencyAlert {self.uuid}>"


class EmergencyResponse(BaseModel):
    __tablename__ = "emergency_responses"

    alert_id = Column(Integer, ForeignKey("emergency_alerts.id"), nullable=False, index=True)
    responder_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)

    response_type = Column(String(50))  # help_on_way, contacted_authorities, etc.
    message = Column(Text)
    eta_minutes = Column(Integer)  # Estimated time of arrival

    def __repr__(self):
        return f"<EmergencyResponse {self.uuid}>"


# New models for additional features
class EmergencyReport(BaseModel):
    __tablename__ = "emergency_reports"

    uuid = Column(UUID(as_uuid=True), default=uuid.uuid4, unique=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=True, index=True)  # Nullable for anonymous reports

    # Location
    latitude = Column(Float, nullable=False)
    longitude = Column(Float, nullable=False)
    address = Column(String(500))

    # Report details
    report_type = Column(String(50), nullable=False)
    description = Column(Text, nullable=False)
    is_anonymous = Column(Boolean, default=False)
    severity = Column(Integer, default=3)  # 1-5 scale
    status = Column(String(20), default="pending")  # pending, investigating, resolved

    def __repr__(self):
        return f"<EmergencyReport {self.uuid}>"


class SafetyCheck(BaseModel):
    __tablename__ = "safety_checks"

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

    message = Column(String(200))
    location_latitude = Column(Float)
    location_longitude = Column(Float)

    def __repr__(self):
        return f"<SafetyCheck {self.uuid}>"
