"""add encrypted commercial license credentials table

Revision ID: 077_license_credentials
Revises: 076_coupon_activity_claims
Create Date: 2026-07-12
"""

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql


revision = "077_license_credentials"
down_revision = "076_coupon_activity_claims"
branch_labels = None
depends_on = None


def _table_exists(bind: sa.engine.Connection, table_name: str) -> bool:
    return table_name in set(sa.inspect(bind).get_table_names())


def upgrade() -> None:
    bind = op.get_bind()
    if _table_exists(bind, "license_credentials"):
        return

    op.create_table(
        "license_credentials",
        sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
        sa.Column("instance_id", sa.String(length=36), nullable=False),
        sa.Column("format_version", sa.SmallInteger(), nullable=False, server_default="1"),
        sa.Column("signing_key_id", sa.String(length=64), nullable=False),
        sa.Column("encryption_key_id", sa.String(length=64), nullable=False),
        sa.Column("lease_scope", sa.String(length=160), nullable=False),
        sa.Column("lease_sequence", sa.BigInteger(), nullable=False),
        sa.Column("nonce", sa.LargeBinary(length=12), nullable=False),
        sa.Column("ciphertext", mysql.LONGBLOB(), nullable=False),
        sa.Column("row_version", sa.BigInteger(), nullable=False, server_default="1"),
        sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
        sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("instance_id", name="uq_license_credentials_instance_id"),
    )
    op.create_index(
        "ix_license_credentials_updated_at",
        "license_credentials",
        ["updated_at"],
    )
    op.create_index(
        "ix_license_credentials_scope_sequence",
        "license_credentials",
        ["lease_scope", "lease_sequence"],
    )


def downgrade() -> None:
    bind = op.get_bind()
    if _table_exists(bind, "license_credentials"):
        op.drop_table("license_credentials")
