-- Migration: 006 – Service tokens for external notification senders
-- Database: SQLite

CREATE TABLE IF NOT EXISTS service_tokens (
    id          TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))),
    name        TEXT NOT NULL,
    token_hash  TEXT NOT NULL UNIQUE,
    created_by  TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    scopes      TEXT NOT NULL DEFAULT '["notify"]',
    is_active   INTEGER NOT NULL DEFAULT 1,
    last_used_at DATETIME,
    expires_at  DATETIME,
    created_at  DATETIME NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_service_tokens_hash    ON service_tokens(token_hash);
CREATE INDEX IF NOT EXISTS idx_service_tokens_creator ON service_tokens(created_by);
