"""Membership model — a user's role inside a workspace."""

from __future__ import annotations

import uuid
from typing import TYPE_CHECKING

from sqlalchemy import Enum as SAEnum
from sqlalchemy import ForeignKey, UniqueConstraint, Uuid
from sqlalchemy.orm import Mapped, mapped_column, relationship

from legate.db.base import Base, TimestampMixin, UUIDPrimaryKeyMixin
from legate.policy.roles import Role

if TYPE_CHECKING:
    from legate.db.models.user import User
    from legate.db.models.workspace import Workspace


class Membership(UUIDPrimaryKeyMixin, TimestampMixin, Base):
    __tablename__ = "memberships"
    __table_args__ = (UniqueConstraint("user_id", "workspace_id", name="uq_membership_user_ws"),)

    user_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False
    )
    workspace_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("workspaces.id", ondelete="CASCADE"), index=True, nullable=False
    )
    role: Mapped[Role] = mapped_column(
        SAEnum(Role, native_enum=False, length=20, values_callable=lambda e: [m.value for m in e]),
        nullable=False,
        default=Role.VIEWER,
    )

    user: Mapped["User"] = relationship(back_populates="memberships")
    workspace: Mapped["Workspace"] = relationship(back_populates="memberships")

    def __repr__(self) -> str:  # pragma: no cover - debug helper
        return f"<Membership user={self.user_id} ws={self.workspace_id} role={self.role}>"
