"""add mps_api_key table for REST API HMAC auth

Revision ID: 4f4d7c147437
Revises: c0236e351476
Create Date: 2026-04-06 15:15:04.347018

"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils.types.uuid

# revision identifiers, used by Alembic.
revision = '4f4d7c147437'
down_revision = 'c0236e351476'
branch_labels = None
depends_on = None


def _table_exists(name):
    conn = op.get_bind()
    result = conn.execute(
        sa.text("SELECT name FROM sqlite_master WHERE type='table' AND name=:name"),
        {"name": name},
    )
    return result.fetchone() is not None


def upgrade():
    if not _table_exists('mps_api_key'):
        op.create_table(
            'mps_api_key',
            sa.Column('id', sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=False),
            sa.Column('shop_id', sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=False),
            sa.Column('public_key', sa.Unicode(length=72), nullable=False),
            sa.Column('secret_key', sa.Unicode(length=136), nullable=False),
            sa.Column('label', sa.Unicode(length=128), nullable=True),
            sa.Column('created_timestamp', sa.BigInteger(), nullable=False),
            sa.Column('last_used_timestamp', sa.BigInteger(), nullable=True),
            sa.Column('is_active', sa.Boolean(), server_default='1', nullable=False),
            sa.ForeignKeyConstraint(['shop_id'], ['mps_shop.id'], ),
            sa.PrimaryKeyConstraint('id'),
        )
        op.create_index('ix_mps_api_key_id', 'mps_api_key', ['id'], unique=False)
        op.create_index('ix_mps_api_key_public_key', 'mps_api_key', ['public_key'], unique=True)
        op.create_index('ix_mps_api_key_shop_id', 'mps_api_key', ['shop_id'], unique=False)


def downgrade():
    op.drop_index('ix_mps_api_key_shop_id', table_name='mps_api_key')
    op.drop_index('ix_mps_api_key_public_key', table_name='mps_api_key')
    op.drop_index('ix_mps_api_key_id', table_name='mps_api_key')
    op.drop_table('mps_api_key')
