# acl/models/acl_entity.py
import uuid
from sqlalchemy import String, Column, ForeignKey, Table
from sqlalchemy.orm import relationship, mapped_column, Mapped
from acl.db_base import Base
from acl.models.group import IkonGroup

UUID_STR = String(36)

aclentity_memberships = Table(
    "aclentity_memberships",
    Base.metadata,
    Column("aclentity_id", UUID_STR, ForeignKey("acl_entities.id"), primary_key=True),
    Column("group_id", UUID_STR, ForeignKey("ikon_groups.id"), primary_key=True),
)

class ACLEntity(Base):
    __tablename__ = "acl_entities"

    id: Mapped[str] = mapped_column(UUID_STR, primary_key=True, default=lambda: str(uuid.uuid4()))
    entity_id: Mapped[str] = mapped_column(UUID_STR, nullable=False)
    account_id: Mapped[str] = mapped_column(UUID_STR, nullable=False)
    user_id: Mapped[str] = mapped_column(UUID_STR, nullable=True)

    memberships: Mapped[list[IkonGroup]] = relationship(
        "IkonGroup",
        secondary=aclentity_memberships,
        lazy="joined",
    )
