import enum
from sqlalchemy import Column, Integer, String, Enum, Text, DateTime, ForeignKey, Boolean
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.core.database import Base

class ProtocolType(str, enum.Enum):
    OIDC = "OIDC"
    SIMPLE_API = "SIMPLE_API"
    NONE = "NONE"

class Application(Base):
    __tablename__ = "applications"

    id = Column(Integer, primary_key=True, index=True)
    app_id = Column(String(32), unique=True, index=True, nullable=False)
    
    # Changed: Store plain secret for HMAC verification capability
    # In production, use Fernet encryption (symmetric) to store this.
    app_secret = Column(String(128), nullable=False)
    
    app_name = Column(String(100), nullable=True)
    icon_url = Column(String(255), nullable=True)
    
    protocol_type = Column(Enum(ProtocolType), default=ProtocolType.SIMPLE_API, nullable=False)
    
    # Stores JSON list of redirect URIs
    redirect_uris = Column(Text, nullable=True)
    
    notification_url = Column(String(255), nullable=True)
    
    # Application description and category
    description = Column(Text, nullable=True)
    category_id = Column(Integer, ForeignKey("app_categories.id"), nullable=True)
    
    # Permanent Access Token for M2M operations (User Mapping Sync)
    access_token = Column(String(128), unique=True, index=True, nullable=True)

    # Ownership & Logic Delete
    owner_id = Column(Integer, ForeignKey("users.id"), nullable=True)
    is_deleted = Column(Boolean, default=False, nullable=False)

    owner = relationship("User") # Link to User model
    category = relationship("AppCategory") # Link to AppCategory model
    
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), server_default=func.now())
