"""add tree sharing tables

Revision ID: 024
Revises: 023
Create Date: 2026-02-07

Adds tree sharing infrastructure:
- visibility field on trees table (private/team/link/public)
- tree_shares: Share tokens for link-based sharing with forking control

Key features:
- Default existing trees to 'team' visibility
- Share tokens are URL-safe (secrets.token_urlsafe)
- Optional expiration for time-limited shares
- allow_forking flag controls whether recipients can fork shared trees
"""
from typing import Sequence, Union

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


# revision identifiers, used by Alembic.
revision: str = '024'
down_revision: Union[str, None] = '023'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Add visibility field to trees with default 'team'
    op.add_column('trees', sa.Column(
        'visibility',
        sa.String(20),
        nullable=False,
        server_default='team',
        comment="Visibility level: private (author only), team (account members), link (share token), public (all users)"
    ))
    op.create_index('ix_trees_visibility', 'trees', ['visibility'])

    # Add CHECK constraint for visibility values
    op.create_check_constraint(
        'ck_trees_visibility',
        'trees',
        "visibility IN ('private', 'team', 'link', 'public')"
    )

    # Create tree_shares table
    op.create_table(
        'tree_shares',
        sa.Column('id', UUID(as_uuid=True), primary_key=True, server_default=sa.text('gen_random_uuid()')),
        sa.Column('tree_id', UUID(as_uuid=True), nullable=False),
        sa.Column('share_token', sa.String(64), nullable=False, unique=True),
        sa.Column('created_by', UUID(as_uuid=True), nullable=False),
        sa.Column('allow_forking', sa.Boolean, nullable=False, server_default='true'),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, server_default=sa.text('now()')),
        sa.Column('expires_at', sa.DateTime(timezone=True), nullable=True),
        sa.ForeignKeyConstraint(['tree_id'], ['trees.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['created_by'], ['users.id'], ondelete='CASCADE')
    )

    # Create indexes for tree_shares
    op.create_index('ix_tree_shares_tree_id', 'tree_shares', ['tree_id'])
    op.create_index('ix_tree_shares_share_token', 'tree_shares', ['share_token'])
    op.create_index('ix_tree_shares_created_by', 'tree_shares', ['created_by'])
    op.create_index('ix_tree_shares_expires_at', 'tree_shares', ['expires_at'])


def downgrade() -> None:
    op.drop_table('tree_shares')
    op.drop_index('ix_trees_visibility', table_name='trees')
    op.drop_constraint('ck_trees_visibility', 'trees', type_='check')
    op.drop_column('trees', 'visibility')
