"""api_keys — machine-to-machine tokens for the /api/v1 public surface.

Other Proxmox LXCs (HR, CRM, …) call Intel Grid via X-API-Key to cross-
reference candidate names against our judicial data. Each key is
labelled, hashed before storage (sha256 of a 32-byte urlsafe token),
and its last usage is tracked for audit / stale-key cleanup.
"""
from alembic import op

revision = "0019"
down_revision = "0018"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.execute(
        """
        CREATE TABLE api_keys (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            label TEXT NOT NULL,
            key_hash CHAR(64) NOT NULL UNIQUE,
            key_prefix CHAR(12) NOT NULL,
            active BOOLEAN NOT NULL DEFAULT true,
            created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
            created_by UUID REFERENCES users(id) ON DELETE SET NULL,
            last_used_at TIMESTAMPTZ,
            use_count INTEGER NOT NULL DEFAULT 0
        );
        CREATE INDEX ix_api_keys_active ON api_keys(active) WHERE active;
        """
    )


def downgrade() -> None:
    op.execute("DROP TABLE IF EXISTS api_keys")
