"""Maps ResolutionFlow users to CW members."""
import uuid
from datetime import datetime, timezone

from sqlalchemy import String, DateTime, ForeignKey, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.dialects.postgresql import UUID

from app.core.database import Base


class PsaMemberMapping(Base):
    __tablename__ = "psa_member_mappings"
    __table_args__ = (
        UniqueConstraint("psa_connection_id", "user_id", name="uq_psa_member_mapping_connection_user"),
        UniqueConstraint("psa_connection_id", "external_member_id", name="uq_psa_member_mapping_connection_member"),
    )

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    psa_connection_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("psa_connections.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    account_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("accounts.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    user_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("users.id", ondelete="CASCADE"),
        nullable=False,
    )
    external_member_id: Mapped[str] = mapped_column(String(100), nullable=False)
    external_member_name: Mapped[str] = mapped_column(String(200), nullable=False)
    matched_by: Mapped[str] = mapped_column(String(50), nullable=False)  # 'auto_email', 'manual_admin', 'manual_self'
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), nullable=False, default=lambda: datetime.now(timezone.utc)
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), nullable=False,
        default=lambda: datetime.now(timezone.utc),
        onupdate=lambda: datetime.now(timezone.utc),
    )

    # Relationships
    psa_connection = relationship("PsaConnection", foreign_keys=[psa_connection_id])
    user = relationship("User", foreign_keys=[user_id])
