from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, JSON, ForeignKey, BigInteger
from sqlalchemy.orm import relationship
from app.core.database import Base
from datetime import datetime

class APIAsset(Base):
    __tablename__ = "api_asset"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(200), nullable=False)
    base_url = Column(String(500), nullable=False)
    swagger_url = Column(String(500), nullable=True)
    auth_type = Column(String(50), default="none")  # none, bearer, api_key, basic
    headers = Column(JSON, default=dict)
    description = Column(Text, nullable=True)
    scan_status = Column(String(20), default="idle")  # idle, scanning, completed, failed
    total_endpoints = Column(Integer, default=0)
    sensitive_endpoints = Column(Integer, default=0)
    created_by = Column(Integer, ForeignKey("sys_user.id"), nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    endpoints = relationship("APIEndpoint", back_populates="asset", cascade="all, delete-orphan")
    creator = relationship("User", foreign_keys=[created_by])

class APIEndpoint(Base):
    __tablename__ = "api_endpoint"
    id = Column(Integer, primary_key=True, index=True)
    asset_id = Column(Integer, ForeignKey("api_asset.id"), nullable=False)
    method = Column(String(10), nullable=False)  # GET, POST, PUT, DELETE, etc.
    path = Column(String(500), nullable=False)
    summary = Column(String(500), nullable=True)
    tags = Column(JSON, default=list)
    parameters = Column(JSON, default=list)
    request_body_schema = Column(JSON, nullable=True)
    response_schema = Column(JSON, nullable=True)
    sensitive_fields = Column(JSON, default=list)  # detected PII fields
    risk_level = Column(String(20), default="low")  # low, medium, high, critical
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)

    asset = relationship("APIAsset", back_populates="endpoints")
