"""Contact folders — hierarchical folders for organizing contacts.

Revision ID: 0022
Revises: 0021_unified_contacts
Create Date: 2026-07-20
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID


revision = "0022_contact_folders"
down_revision = "0021_unified_contacts"


def upgrade():
    # 1. Create contact_folders table
    op.create_table(
        "contact_folders",
        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, index=True),
        sa.Column("name", sa.String(255), nullable=False),
        sa.Column("parent_id", UUID(as_uuid=True), sa.ForeignKey("contact_folders.id", ondelete="CASCADE"), nullable=True),
        sa.Column("user_id", UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
        sa.Column("sort_order", sa.Integer, nullable=False, server_default="0"),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
        sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
    )
    op.create_index("ix_contact_folders_tenant_parent", "contact_folders", ["tenant_id", "parent_id"])
    op.create_index("ix_contact_folders_user", "contact_folders", ["user_id"])

    # 2. Add folder_id column to contacts
    op.add_column(
        "contacts",
        sa.Column("folder_id", UUID(as_uuid=True), sa.ForeignKey("contact_folders.id", ondelete="SET NULL"), nullable=True),
    )
    op.create_index("ix_contacts_folder_id", "contacts", ["folder_id"])


def downgrade():
    op.drop_index("ix_contacts_folder_id", table_name="contacts")
    op.drop_column("contacts", "folder_id")
    op.drop_index("ix_contact_folders_user", table_name="contact_folders")
    op.drop_index("ix_contact_folders_tenant_parent", table_name="contact_folders")
    op.drop_table("contact_folders")
