-- 002_api_keys.sql
-- Dynamic, self-managed API keys for ops-api consumers.
--
-- ops-api validates the X-API-Key header against (a) the static keys loaded
-- from Infisical and (b) the active rows in this table. New consumers can be
-- minted at runtime via POST /api/v1/admin/api-keys — no rebuild required.
--
-- Applied automatically at startup by APIKeyService.EnsureSchema(); kept here
-- as the canonical record. Only the SHA-256 hash of each key is stored; the
-- plaintext is returned exactly once at creation time.

-- `scopes` limits which calls a key may make (e.g. {ldap:read}); the static
-- Infisical keys carry an implicit wildcard. See pkg/types/scopes.go.

CREATE TABLE IF NOT EXISTS admin.api_keys (
    id           uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    name         text NOT NULL UNIQUE,
    key_hash     text NOT NULL UNIQUE,
    key_prefix   text NOT NULL,
    scopes       text[] NOT NULL DEFAULT '{}',
    active       boolean NOT NULL DEFAULT true,
    created_at   timestamptz NOT NULL DEFAULT now(),
    last_used_at timestamptz,
    created_by   text
);

CREATE INDEX IF NOT EXISTS idx_api_keys_active ON admin.api_keys (active) WHERE active;
