from csirtmu.core.sqlalchemy.types import StringArray
from sqlalchemy import Integer, UniqueConstraint
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from csirtmu.perun_sync.perun_sync.types import PerunUserStruct


class Base(DeclarativeBase):
    __abstract__ = True


class PerunUser(Base):
    __tablename__ = "perun_user"
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    facility: Mapped[str]
    perun_id: Mapped[str] = mapped_column(nullable=False)
    login_mu: Mapped[str] = mapped_column(nullable=False)
    scoped_login_mu: Mapped[str] = mapped_column(nullable=False)
    display_name: Mapped[str] = mapped_column(nullable=False)
    preferred_mail: Mapped[str] = mapped_column(nullable=False)
    aliases: Mapped[list[str]] = mapped_column(StringArray, nullable=True)

    __table_args__ = (
        UniqueConstraint("login_mu", "facility", name="perun_propagation_user_facility_unique"),
        {"schema": "public"},
    )

    def to_struct(self) -> PerunUserStruct:
        return PerunUserStruct(
            facility=self.facility,
            perun_id=self.perun_id,
            login_mu=self.login_mu,
            scoped_login_mu=self.scoped_login_mu,
            display_name=self.display_name,
            preferred_mail=self.preferred_mail,
            aliases=self.aliases or [],
        )
