"""Personal API tokens (apitokens)

Adds the apitokens table: personal access tokens that let scripts and
integrations authenticate as a user without the hourly-expiring login JWT.
Only the sha256 hash of each secret is stored.

Idempotent guard so it is safe on a partially-migrated box; real downgrade.

Revision ID: 7d21_apitokens
Revises: 7d20_relationshiptypepropagations
Create Date: 2026-07-12

"""
from alembic import op
import sqlalchemy as sa


revision = '7d21_apitokens'
down_revision = '7d20_relationshiptypepropagations'
branch_labels = None
depends_on = None


def upgrade():
    bind = op.get_bind()
    insp = sa.inspect(bind)

    if 'apitokens' in insp.get_table_names():
        return

    op.create_table(
        'apitokens',
        sa.Column('tokenid', sa.Integer(), primary_key=True),
        sa.Column('userid', sa.Integer(), nullable=False),
        sa.Column('name', sa.String(length=100), nullable=False),
        sa.Column('tokenprefix', sa.String(length=16), nullable=True),
        sa.Column('tokenhash', sa.String(length=64), nullable=False),
        sa.Column('expiresat', sa.DateTime(), nullable=True),
        sa.Column('lastusedat', sa.DateTime(), nullable=True),
        sa.Column('createddate', sa.DateTime(), nullable=False),
        sa.Column('modifieddate', sa.DateTime(), nullable=False),
        sa.Column('isactive', sa.Boolean(), nullable=False, server_default='1'),
        sa.ForeignKeyConstraint(['userid'], ['users.userid']),
        sa.UniqueConstraint('tokenhash', name='uq_apitoken_tokenhash'),
    )
    op.create_index('ix_apitokens_userid', 'apitokens', ['userid'])
    op.create_index('ix_apitokens_tokenprefix', 'apitokens', ['tokenprefix'])
    op.create_index('ix_apitokens_tokenhash', 'apitokens', ['tokenhash'])


def downgrade():
    bind = op.get_bind()
    insp = sa.inspect(bind)

    if 'apitokens' not in insp.get_table_names():
        return

    op.drop_index('ix_apitokens_tokenhash', table_name='apitokens')
    op.drop_index('ix_apitokens_tokenprefix', table_name='apitokens')
    op.drop_index('ix_apitokens_userid', table_name='apitokens')
    op.drop_table('apitokens')
