from sqlalchemy import Column, String, Integer, Boolean, DateTime, ForeignKey, Text, JSON
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.db.database import Base
import uuid

class License(Base):
    __tablename__ = "licenses"
    
    id = Column(Integer, primary_key=True, index=True)
    license_key = Column(String, unique=True, index=True, default=lambda: str(uuid.uuid4()))
    product_id = Column(String, nullable=False)
    customer_email = Column(String, nullable=False)
    customer_name = Column(String)
    
    max_activations = Column(Integer, default=1)
    is_active = Column(Boolean, default=True)
    expires_at = Column(DateTime, nullable=True)
    
    created_at = Column(DateTime, server_default=func.now())
    updated_at = Column(DateTime, onupdate=func.now())
    
    activations = relationship("Activation", back_populates="license")
    
class Activation(Base):
    __tablename__ = "activations"
    
    id = Column(Integer, primary_key=True, index=True)
    license_id = Column(Integer, ForeignKey("licenses.id"))
    machine_id = Column(String, nullable=False)
    hardware_hash = Column(String, nullable=False)
    
    activation_date = Column(DateTime, server_default=func.now())
    last_heartbeat = Column(DateTime, server_default=func.now())
    is_active = Column(Boolean, default=True)
    
    os_info = Column(JSON)
    app_version = Column(String)
    
    license = relationship("License", back_populates="activations")
    
class Version(Base):
    __tablename__ = "versions"
    
    id = Column(Integer, primary_key=True, index=True)
    version_number = Column(String, unique=True, nullable=False)
    release_date = Column(DateTime, server_default=func.now())
    is_mandatory = Column(Boolean, default=False)
    min_version = Column(String)
    
    download_url = Column(String)
    release_notes = Column(Text)
    
    created_at = Column(DateTime, server_default=func.now())
    
class ApiKey(Base):
    __tablename__ = "api_keys"
    
    id = Column(Integer, primary_key=True, index=True)
    key = Column(String, unique=True, index=True, default=lambda: str(uuid.uuid4()))
    name = Column(String, nullable=False)
    is_active = Column(Boolean, default=True)
    
    created_at = Column(DateTime, server_default=func.now())
    last_used = Column(DateTime)