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


class APIKeyScope(str, enum.Enum):
    READ_PROJECTS = "read:projects"
    READ_TASKS = "read:tasks"
    READ_SUBMISSIONS = "read:submissions"
    READ_USERS = "read:users"
    WRITE_TASKS = "write:tasks"
    WRITE_SUBMISSIONS = "write:submissions"
    ADMIN_USERS = "admin:users"
    FULL_ACCESS = "full:access"


class APIKey(Base):
    __tablename__ = "api_keys"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    key_hash = Column(String, unique=True, index=True, nullable=False)
    name = Column(String, nullable=False)
    scopes = Column(Text, nullable=False)  # JSON string of scopes
    is_active = Column(Boolean, default=True, nullable=False)
    expires_at = Column(DateTime(timezone=True), nullable=True)
    last_used_at = Column(DateTime(timezone=True), nullable=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())

    # Relationships
    user = relationship("User", back_populates="api_keys")

    def __repr__(self):
        return f"<APIKey(id={self.id}, name='{self.name}', user_id={self.user_id})>"