"""مدل TenantMembership: رابطه واقعی کاربر ↔ tenant (فاز Onboarding).

هر کاربر می‌تواند در آینده عضو چند tenant باشد؛ نقش و وضعیت عضویت او در هر
tenant مستقل از نقش سراسری (User.role / JWT roles) نگهداری می‌شود.
"""
from __future__ import annotations

import uuid

from sqlalchemy import Boolean
from sqlalchemy import Enum as SAEnum
from sqlalchemy import ForeignKey, Index, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column

from app.core.database import Base
from app.models.base import TimestampMixin, UUIDPrimaryKeyMixin
from app.models.enums import MembershipStatus, TenantMembershipRole
from app.models.types import GUID


class TenantMembership(UUIDPrimaryKeyMixin, TimestampMixin, Base):
    __tablename__ = "tenant_memberships"

    tenant_id: Mapped[uuid.UUID] = mapped_column(
        GUID(), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False
    )
    user_id: Mapped[uuid.UUID] = mapped_column(
        GUID(), ForeignKey("users.id", ondelete="CASCADE"), nullable=False
    )
    role: Mapped[TenantMembershipRole] = mapped_column(
        SAEnum(
            TenantMembershipRole,
            name="tenant_membership_role",
            values_callable=lambda enum_cls: [item.value for item in enum_cls],
        ),
        default=TenantMembershipRole.TENANT_VIEWER,
        nullable=False,
    )
    status: Mapped[MembershipStatus] = mapped_column(
        SAEnum(
            MembershipStatus,
            name="tenant_membership_status",
            values_callable=lambda enum_cls: [item.value for item in enum_cls],
        ),
        default=MembershipStatus.ACTIVE,
        nullable=False,
    )
    is_owner: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)

    __table_args__ = (
        UniqueConstraint("tenant_id", "user_id", name="uq_tenant_membership_tenant_user"),
        Index("ix_tenant_memberships_tenant_id", "tenant_id"),
        Index("ix_tenant_memberships_user_id", "user_id"),
        Index("ix_tenant_memberships_role", "role"),
        Index("ix_tenant_memberships_status", "status"),
    )

    def __repr__(self) -> str:  # pragma: no cover
        return (
            f"<TenantMembership tenant_id={self.tenant_id} user_id={self.user_id} "
            f"role={self.role}>"
        )
