from typing import TYPE_CHECKING, Optional
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, ForeignKey, JSON, Float
from sqlalchemy.orm import Mapped, relationship
from sqlalchemy.sql import func
from app.database.database import Base


class UserNotification(Base):
    """User notification model for storing push notifications"""
    __tablename__ = "user_notifications"
    
    notification_id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey("users.user_id", ondelete="CASCADE"), nullable=False, index=True)
    
    # Notification content
    title = Column(String(255), nullable=False)
    body = Column(Text, nullable=False)
    image_url = Column(String(500), nullable=True)
    
    # Notification type and metadata
    notification_type = Column(String(100), nullable=False, index=True)  # e.g., "favorite_product_travel", "favorite_product"
    data_payload = Column(JSON, nullable=True)  # Store the data dict (product_id, store_id, listing_id, distance, etc.)
    
    # Related entity IDs (for quick filtering)
    product_id = Column(Integer, ForeignKey("products.product_id", ondelete="SET NULL"), nullable=True, index=True)
    store_id = Column(Integer, ForeignKey("stores.store_id", ondelete="SET NULL"), nullable=True, index=True)
    listing_id = Column(Integer, ForeignKey("product_listings.listing_id", ondelete="SET NULL"), nullable=True, index=True)
    
    # Distance information (for travel mode notifications)
    distance_km = Column(Float, nullable=True)
    
    # Notification status
    is_read = Column(Boolean, default=False, nullable=False, index=True)
    sent_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True)
    read_at = Column(DateTime(timezone=True), nullable=True)
    
    # FCM delivery status (optional - to track if push notification was sent successfully)
    fcm_sent = Column(Boolean, default=False, nullable=False)
    fcm_error = Column(Text, nullable=True)  # Store error message if FCM failed
    
    # Timestamps
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
    
    # Relationships
    if TYPE_CHECKING:
        from app.models.user.user_model import User  # pragma: no cover
        from app.models.listing.products import Product, ProductListing  # pragma: no cover
        from app.models.staff.store_model import Store  # pragma: no cover
    
    user: Mapped["User"] = relationship("User", back_populates="notifications")
    product = relationship("Product")
    store = relationship("Store")
    listing = relationship("ProductListing")

