"""
API key models for third-party access.
"""
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Boolean, JSON
from sqlalchemy.orm import relationship
from datetime import datetime, timedelta
from ...shared.config.database import Base

class APIKey(Base):
    __tablename__ = 'api_keys'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    name = Column(String(255), nullable=False)
    key_hash = Column(String(255), unique=True, nullable=False, index=True)  # Hashed API key
    key_prefix = Column(String(20), nullable=False, index=True)  # First 8 chars for identification
    
    # Permissions
    scopes = Column(JSON, nullable=False)  # List of allowed scopes/permissions
    rate_limit = Column(Integer, default=100, nullable=False)  # Requests per minute
    
    # Status
    is_active = Column(Boolean, default=True, nullable=False, index=True)
    
    # Expiration
    expires_at = Column(DateTime, nullable=True, index=True)
    
    # Metadata
    description = Column(Text, nullable=True)
    last_used_at = Column(DateTime, nullable=True)
    created_by = Column(Integer, ForeignKey('users.id'), nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    # Relationships
    creator = relationship('User', foreign_keys=[created_by])
    
    @property
    def is_expired(self) -> bool:
        """Check if API key is expired."""
        if not self.expires_at:
            return False
        return datetime.utcnow() > self.expires_at
    
    @property
    def is_valid(self) -> bool:
        """Check if API key is valid (active and not expired)."""
        return self.is_active and not self.is_expired

