"""contact_merge_history table

Revision ID: 0030_contact_merge_history
Revises: 0029_saved_filters
Create Date: 2025-07-23
"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID, JSONB

# revision identifiers
revision = "0030_contact_merge_history"
down_revision = "0029_saved_filters"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "contact_merge_history",
        sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
        sa.Column("tenant_id", UUID(as_uuid=True), nullable=False),
        sa.Column("source_contact_id", UUID(as_uuid=True), sa.ForeignKey("contacts.id", ondelete="SET NULL"), nullable=False),
        sa.Column("target_contact_id", UUID(as_uuid=True), sa.ForeignKey("contacts.id", ondelete="CASCADE"), nullable=False),
        sa.Column("merged_fields", JSONB, nullable=False, server_default=sa.text("'{}'::jsonb")),
        sa.Column("merged_by", UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
        sa.Column("note", sa.Text, nullable=True),
        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.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
    )
    op.create_index("ix_contact_merge_history_tenant", "contact_merge_history", ["tenant_id"])
    op.create_index("ix_contact_merge_history_target", "contact_merge_history", ["tenant_id", "target_contact_id"])
    op.create_index("ix_contact_merge_history_source", "contact_merge_history", ["tenant_id", "source_contact_id"])


def downgrade() -> None:
    op.drop_index("ix_contact_merge_history_source", table_name="contact_merge_history")
    op.drop_index("ix_contact_merge_history_target", table_name="contact_merge_history")
    op.drop_index("ix_contact_merge_history_tenant", table_name="contact_merge_history")
    op.drop_table("contact_merge_history")
