from arepo.models import Base

from sqlalchemy.orm import relationship
from sqlalchemy import Column, Integer, String, ForeignKey, Float, DateTime, ForeignKeyConstraint


class TagModel(Base):
    __tablename__ = "tag"

    id = Column('id', Integer, primary_key=True)
    name = Column('name', String, nullable=False)
    references = relationship("ReferenceModel", secondary="reference_tag", backref='tags')


class ReferenceModel(Base):
    __tablename__ = "reference"

    id = Column('id', String, primary_key=True)
    url = Column('url', String, nullable=False)
    vulnerability_id = Column(String, ForeignKey('vulnerability.id'))


class ReferenceTagModel(Base):
    __tablename__ = 'reference_tag'
    __table_args__ = (
        ForeignKeyConstraint(('reference_id',), ['reference.id']),
        ForeignKeyConstraint(('tag_id',), ['tag.id']),
    )

    reference_id = Column(String, ForeignKey('reference.id'), primary_key=True)
    tag_id = Column(Integer, ForeignKey('tag.id'), primary_key=True)


class VulnerabilityModel(Base):
    __tablename__ = "vulnerability"

    id = Column('id', String, primary_key=True)
    description = Column('description', String, nullable=True)
    assigner = Column('assigner', String, nullable=False)
    severity = Column('severity', String, nullable=True)
    exploitability = Column('exploitability', Float, nullable=True)
    impact = Column('impact', Float, nullable=True)
    published_date = Column('published_date', DateTime, nullable=False)
    last_modified_date = Column('last_modified_date', DateTime, nullable=False)
    references = relationship("ReferenceModel", backref="vulnerability")
    configurations = relationship("ConfigurationModel", backref="vulnerability")
    commits = relationship("CommitModel", backref="vulnerability")


class VulnerabilityCWEModel(Base):
    __tablename__ = 'vulnerability_cwe'
    __table_args__ = (
        ForeignKeyConstraint(('vulnerability_id',), ['vulnerability.id']),
        ForeignKeyConstraint(('cwe_id',), ['cwe.id'])
    )

    vulnerability_id = Column(String, ForeignKey('vulnerability.id'), primary_key=True)
    cwe_id = Column(Integer, ForeignKey('cwe.id'), primary_key=True)
