"""add organizations

Revision ID: 70914b334cfb
Revises:
Create Date: 2026-04-23 12:27:56.220214+00:00

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = '70914b334cfb'
down_revision: Union[str, None] = '0b9c1d2e3f4a'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # ADD COLUMN IF NOT EXISTS — idempotent (safe on DBs bootstrapped via create_all)
    op.execute("ALTER TABLE decisions ADD COLUMN IF NOT EXISTS organization_id UUID REFERENCES organizations(id)")
    op.execute("CREATE INDEX IF NOT EXISTS ix_decisions_organization_id ON decisions (organization_id)")
    op.execute("ALTER TABLE documents ADD COLUMN IF NOT EXISTS organization_id UUID REFERENCES organizations(id)")
    op.execute("CREATE INDEX IF NOT EXISTS ix_documents_organization_id ON documents (organization_id)")
    op.execute("ALTER TABLE mandates ADD COLUMN IF NOT EXISTS organization_id UUID REFERENCES organizations(id)")
    op.execute("CREATE INDEX IF NOT EXISTS ix_mandates_organization_id ON mandates (organization_id)")
    op.execute("ALTER TABLE voting_protocols ADD COLUMN IF NOT EXISTS organization_id UUID REFERENCES organizations(id)")
    op.execute("CREATE INDEX IF NOT EXISTS ix_voting_protocols_organization_id ON voting_protocols (organization_id)")


def downgrade() -> None:
    op.drop_index(op.f('ix_voting_protocols_organization_id'), table_name='voting_protocols')
    op.drop_column('voting_protocols', 'organization_id')
    op.drop_index(op.f('ix_mandates_organization_id'), table_name='mandates')
    op.drop_column('mandates', 'organization_id')
    op.drop_index(op.f('ix_documents_organization_id'), table_name='documents')
    op.drop_column('documents', 'organization_id')
    op.drop_index(op.f('ix_decisions_organization_id'), table_name='decisions')
    op.drop_column('decisions', 'organization_id')
