"""Add psa_member_mappings table for user-to-CW-member mapping.

Revision ID: 061
Revises: 060
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

revision = "061"
down_revision = "060"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "psa_member_mappings",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column(
            "psa_connection_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("psa_connections.id", ondelete="CASCADE"),
            nullable=False,
            index=True,
        ),
        sa.Column(
            "user_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("users.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("external_member_id", sa.String(100), nullable=False),
        sa.Column("external_member_name", sa.String(200), nullable=False),
        sa.Column("matched_by", sa.String(50), nullable=False),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.func.now(),
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.func.now(),
        ),
        sa.UniqueConstraint(
            "psa_connection_id", "user_id",
            name="uq_psa_member_mapping_connection_user",
        ),
        sa.UniqueConstraint(
            "psa_connection_id", "external_member_id",
            name="uq_psa_member_mapping_connection_member",
        ),
    )


def downgrade() -> None:
    op.drop_table("psa_member_mappings")
