"""add_agent_fields_and_nullable_tenant

Revision ID: add_agent_fields
Revises: 4ca4b9958baf
Create Date: 2025-12-02 19:30:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


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


def upgrade() -> None:
    # Add new columns to agents table
    op.add_column('agents', sa.Column('version', sa.String(length=50), nullable=False, server_default=''))
    op.add_column('agents', sa.Column('status', sa.String(length=20), nullable=False, server_default='offline'))
    op.add_column('agents', sa.Column('token', sa.Text(), nullable=False, server_default=''))

    # Create index on status for efficient queries
    op.create_index(op.f('ix_agents_status'), 'agents', ['status'], unique=False)

    # Make tenant_id nullable (agents can register without a tenant)
    op.alter_column('agents', 'tenant_id',
                    existing_type=sa.UUID(),
                    nullable=True)


def downgrade() -> None:
    # Make tenant_id NOT NULL again (will fail if there are rows with NULL tenant_id)
    op.alter_column('agents', 'tenant_id',
                    existing_type=sa.UUID(),
                    nullable=False)

    # Drop the status index
    op.drop_index(op.f('ix_agents_status'), table_name='agents')

    # Drop new columns
    op.drop_column('agents', 'token')
    op.drop_column('agents', 'status')
    op.drop_column('agents', 'version')
