"""
SQLAlchemy model for API keys.

This module defines the database model for storing API keys used for public API authentication.
"""

from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Boolean
from sqlalchemy.orm import relationship

from app.database import Base


class ApiKey(Base):
    """
    Model for storing user API keys.
    
    Attributes:
        id: Primary key
        user_id: Foreign key to users table
        key_hash: Hashed API key (never store plain keys)
        key_prefix: First 8 characters of key for identification
        is_active: Whether the key is active
        rate_limit: Rate limit per minute for this key
        last_used_at: Timestamp of last API usage
        created_at: Timestamp when key was created
    """
    __tablename__ = "api_keys"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
    key_hash = Column(String(255), nullable=False, unique=True, index=True)
    key_prefix = Column(String(8), nullable=False, index=True)
    is_active = Column(Boolean, default=True, nullable=False)
    rate_limit = Column(Integer, default=100, nullable=False)  # Default: 100 req/min
    last_used_at = Column(DateTime, nullable=True)
    created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
    
    # Relationships
    user = relationship("User", back_populates="api_keys")
    
    def __repr__(self) -> str:
        return f"<ApiKey(id={self.id}, user_id={self.user_id}, prefix={self.key_prefix})>"
    
    def to_dict(self) -> dict:
        """Convert API key model to dictionary (safe version)."""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'key_prefix': self.key_prefix,
            'is_active': self.is_active,
            'rate_limit': self.rate_limit,
            'last_used_at': self.last_used_at.isoformat() if self.last_used_at else None,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
