"""
Group Model
"""
from sqlalchemy import Column, Integer, String, Text, Table, ForeignKey
from sqlalchemy.orm import relationship
from app.models.base import Base, TimestampMixin

# Association Table for User-Group Many-to-Many
user_groups = Table(
    'user_groups',
    Base.metadata,
    Column('user_id', Integer, ForeignKey('users.id'), primary_key=True),
    Column('group_id', Integer, ForeignKey('groups.id'), primary_key=True)
)

# Association Table for Asset-Group Many-to-Many
asset_groups = Table(
    'asset_groups',
    Base.metadata,
    Column('asset_id', Integer, ForeignKey('assets.id'), primary_key=True),
    Column('group_id', Integer, ForeignKey('groups.id'), primary_key=True)
)


class Group(Base, TimestampMixin):
    __tablename__ = "groups"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), unique=True, nullable=False)
    description = Column(Text, nullable=True)
    
    # Policy Assignment
    policy_id = Column(Integer, ForeignKey("policies.id"), nullable=True)

    # Relationships
    users = relationship("User", secondary=user_groups, back_populates="groups")
    assets = relationship("Asset", secondary=asset_groups, back_populates="groups")
    vulnerabilities = relationship("Vulnerability", back_populates="group")
    policy = relationship("Policy")
