-- Migration 007: Create management audit log table
-- Date: 2025-11-11
-- Description: Track all management portal actions for security and compliance

-- ============================================================================
-- Table: management_audit_log
-- Purpose: Audit trail for all user actions via management portal
-- ============================================================================
CREATE TABLE IF NOT EXISTS management_audit_log (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    group_id TEXT,                        -- Group ID (NULL if token validation failed)
    management_token TEXT,                -- Management token used (partially masked in queries)
    action TEXT NOT NULL,                 -- Action type: 'validate_token', 'revoke_consent', 'update_metadata', 'add_image', 'delete_image', 'delete_group'
    success BOOLEAN NOT NULL DEFAULT 1,   -- Whether action succeeded
    error_message TEXT,                   -- Error message if action failed
    ip_address TEXT,                      -- Client IP address
    user_agent TEXT,                      -- Client user agent
    request_data TEXT,                    -- JSON of request data (sanitized)
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    
    -- Foreign key (optional, NULL if group was deleted)
    FOREIGN KEY (group_id) REFERENCES groups(group_id) ON DELETE SET NULL
);

-- ============================================================================
-- Indexes for query performance
-- ============================================================================
CREATE INDEX IF NOT EXISTS idx_audit_group_id ON management_audit_log(group_id);
CREATE INDEX IF NOT EXISTS idx_audit_action ON management_audit_log(action);
CREATE INDEX IF NOT EXISTS idx_audit_success ON management_audit_log(success);
CREATE INDEX IF NOT EXISTS idx_audit_created_at ON management_audit_log(created_at);
CREATE INDEX IF NOT EXISTS idx_audit_ip ON management_audit_log(ip_address);
