"""
Migrazione 0014: tabella pec_contacts (Feature 6 – Rubrica indirizzi PEC).
"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

revision = "0014"
down_revision = "0013"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "pec_contacts",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column(
            "tenant_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("tenants.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("email", sa.String(255), nullable=False),
        sa.Column("name", sa.String(255), nullable=True),
        sa.Column("organization", sa.String(255), nullable=True),
        sa.Column("notes", sa.Text, nullable=True),
        sa.Column("is_favorite", sa.Boolean, nullable=False, server_default="false"),
        # auto_saved=True: contatto creato automaticamente dal sistema durante la sync
        # auto_saved=False: contatto aggiunto manualmente dall'utente
        sa.Column("auto_saved", sa.Boolean, nullable=False, server_default="false"),
        sa.Column(
            "created_by",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("users.id", ondelete="SET NULL"),
            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.UniqueConstraint("tenant_id", "email", name="uq_pec_contact_email_tenant"),
    )
    op.create_index("idx_pec_contacts_tenant", "pec_contacts", ["tenant_id"])
    op.create_index("idx_pec_contacts_email", "pec_contacts", ["tenant_id", "email"])


def downgrade() -> None:
    op.drop_index("idx_pec_contacts_email", table_name="pec_contacts")
    op.drop_index("idx_pec_contacts_tenant", table_name="pec_contacts")
    op.drop_table("pec_contacts")
