-- Migration 005: Add audit logging table
--
-- Records sensitive operations for security and compliance:
-- - Authentication events (login, logout, failed attempts)
-- - Configuration changes
-- - User management operations
-- - Data access and exports

------------------------------------------------------------------------
-- Audit log table
------------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS audit_log (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    -- Event classification
    action          TEXT    NOT NULL,
    category        TEXT    NOT NULL
                        CHECK(category IN (
                            'auth',
                            'user_management',
                            'branding',
                            'system_config',
                            'data_access',
                            'data_export',
                            'permission_change',
                            'other'
                        )),
    -- Actor information
    user_id         TEXT,
    username        TEXT,
    ip_address      TEXT,
    user_agent      TEXT,
    -- Event details
    resource_type   TEXT,
    resource_id     TEXT,
    details         TEXT    NOT NULL DEFAULT '{}',  -- JSON with action-specific data
    -- Outcome
    status          TEXT    NOT NULL
                        CHECK(status IN ('success', 'failure', 'denied'))
                        DEFAULT 'success',
    -- Timestamp (ms since epoch)
    created_at      INTEGER NOT NULL
);

-- Indexes for common query patterns
CREATE INDEX IF NOT EXISTS idx_audit_log_created_at ON audit_log(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_log_user_id ON audit_log(user_id);
CREATE INDEX IF NOT EXISTS idx_audit_log_action ON audit_log(action);
CREATE INDEX IF NOT EXISTS idx_audit_log_category ON audit_log(category);
CREATE INDEX IF NOT EXISTS idx_audit_log_status ON audit_log(status);
-- Composite index for filtered queries
CREATE INDEX IF NOT EXISTS idx_audit_log_category_created ON audit_log(category, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_log_user_created ON audit_log(user_id, created_at DESC);

------------------------------------------------------------------------
-- End of migration
------------------------------------------------------------------------