MindPeeker Logo
Specifications

Data Models & Schemas

Complete data models and schema definitions for MindPeeker platform

Core Data Models

User Model

interface User {
  // Primary identification
  id: string;                    // UUID v4
  email: string;                 // Unique email address
  username: string;              // Unique username
  password_hash: string;         // Bcrypt hash
  
  // Subscription and billing
  tier: UserTier;                // Subscription tier
  credits: number;               // Available credits
  subscription_id?: string;      // Stripe subscription ID
  billing_address?: Address;     // Billing information
  
  // Profile information
  first_name?: string;           // First name
  last_name?: string;            // Last name
  organization?: string;         // Company/organization
  phone?: string;                // Phone number
  timezone: string;              // User timezone
  language: string;              // Preferred language
  
  // Preferences and settings
  preferences: UserPreferences;  // User preferences
  notifications: NotificationSettings; // Notification settings
  
  // Security and authentication
  email_verified: boolean;       // Email verification status
  two_factor_enabled: boolean;   // 2FA status
  api_keys: ApiKey[];            // API keys
  refresh_tokens: RefreshToken[]; // Active refresh tokens
  
  // Metadata and timestamps
  metadata: Record<string, any>;  // Custom metadata
  created_at: Date;              // Account creation
  updated_at: Date;              // Last update
  last_login?: Date;             // Last login timestamp
  deleted_at?: Date;             // Soft delete timestamp
}

enum UserTier {
  BASIC = 'basic',
  PROFESSIONAL = 'professional',
  ENTERPRISE = 'enterprise'
}

interface UserPreferences {
  theme: 'light' | 'dark' | 'auto';
  language: string;
  timezone: string;
  currency: string;
  date_format: string;
  time_format: '12h' | '24h';
  default_session_type: SessionType;
  auto_save: boolean;
  public_profile: boolean;
}

interface NotificationSettings {
  email: boolean;
  push: boolean;
  sms: boolean;
  session_completed: boolean;
  analysis_ready: boolean;
  billing_alerts: boolean;
  marketing_emails: boolean;
  security_alerts: boolean;
}

Session Model

interface Session {
  // Primary identification
  id: string;                    // UUID v4
  user_id: string;               // User UUID
  cue: string;                   // The psychic query/cue
  
  // Session configuration
  session_type: SessionType;     // Type of psychic session
  parameters: SessionParameters; // Session parameters
  priority: Priority;           // Processing priority
  
  // Status and timing
  status: SessionStatus;         // Current status
  created_at: Date;              // Session creation
  started_at?: Date;             // Processing start
  completed_at?: Date;           // Completion time
  estimated_completion?: Date;  // Estimated completion
  
  // Results and analysis
  confidence_score?: number;     // Overall confidence (0-1)
  results?: SessionResults;      // Analysis results
  analysis_history: AnalysisStep[]; // Processing steps
  
  // Resource tracking
  credits_required: number;      // Credits needed
  credits_used?: number;         // Credits actually used
  processing_time?: number;      // Processing time in seconds
  
  // Metadata and classification
  metadata: SessionMetadata;     // Session metadata
  tags: string[];                // User-defined tags
  category?: string;             // Auto-categorized
  sensitivity: SensitivityLevel; // Data sensitivity
  
  // Quality and validation
  quality_score?: number;        // Result quality score
  validation_status?: ValidationStatus; // Validation results
  reviewer_notes?: string;       // Human reviewer notes
  
  // Relationships
  analyses: Analysis[];          // Related analyses
  webhooks_delivered: WebhookDelivery[]; // Webhook deliveries
}

enum SessionType {
  REMOTE_VIEWING = 'remote_viewing',
  DOWSING = 'dowsing',
  PRECOGNITION = 'precognition',
  INTUITIVE_ANALYSIS = 'intuitive_analysis',
  MEDIUMSHIP = 'mediumship',
  PSYCHOMETRY = 'psychometry'
}

enum SessionStatus {
  PENDING = 'pending',
  QUEUED = 'queued',
  PROCESSING = 'processing',
  COMPLETED = 'completed',
  FAILED = 'failed',
  CANCELLED = 'cancelled',
  EXPIRED = 'expired'
}

enum Priority {
  LOW = 'low',
  NORMAL = 'normal',
  HIGH = 'high',
  URGENT = 'urgent'
}

interface SessionParameters {
  // Core parameters
  duration?: number;             // Session duration in seconds
  confidence_threshold: number;  // Minimum confidence threshold
  analysis_types: AnalysisType[]; // Types of analysis to perform
  
  // Model configuration
  model_version?: string;         // Specific model version
  temperature?: number;          // AI temperature parameter
  max_tokens?: number;          // Maximum tokens to generate
  
  // Output preferences
  output_format: OutputFormat;   // Desired output format
  language: string;              // Output language
  detail_level: DetailLevel;     // Level of detail required
  
  // Advanced options
  cross_validation: boolean;      // Enable cross-validation
  ensemble_models: boolean;      // Use model ensemble
  custom_weights?: Record<string, number>; // Custom model weights
}

enum AnalysisType {
  VISUAL = 'visual',
  SPATIAL = 'spatial',
  TEMPORAL = 'temporal',
  EMOTIONAL = 'emotional',
  CONCEPTUAL = 'conceptual',
  NUMERICAL = 'numerical'
}

enum OutputFormat {
  JSON = 'json',
  TEXT = 'text',
  STRUCTURED = 'structured',
  SUMMARY = 'summary',
  DETAILED = 'detailed'
}

enum DetailLevel {
  BASIC = 'basic',
  STANDARD = 'standard',
  COMPREHENSIVE = 'comprehensive',
  EXHAUSTIVE = 'exhaustive'
}

interface SessionResults {
  // Core results
  summary: string;               // Executive summary
  key_findings: KeyFinding[];    // Key insights
  confidence_score: number;      // Overall confidence
  
  // Detailed analysis
  detailed_analysis: DetailedAnalysis; // Complete analysis
  recommendations: string[];     // Actionable recommendations
  
  // Supporting data
  evidence: Evidence[];          // Supporting evidence
  confidence_breakdown: ConfidenceBreakdown; // Confidence by category
  alternative_interpretations: AlternativeInterpretation[]; // Alternative views
  
  // Metadata
  processing_metadata: ProcessingMetadata; // Processing information
  model_information: ModelInformation; // Model details
}

interface KeyFinding {
  type: string;                  // Type of finding
  description: string;           // Description
  confidence: number;            // Confidence score (0-1)
  importance: ImportanceLevel;   // Importance level
  supporting_evidence: string[]; // Supporting evidence IDs
  timestamp?: Date;              // When this finding was identified
}

enum ImportanceLevel {
  LOW = 'low',
  MEDIUM = 'medium',
  HIGH = 'high',
  CRITICAL = 'critical'
}

interface DetailedAnalysis {
  // Spatial analysis
  spatial_data?: SpatialAnalysis;
  
  // Temporal analysis
  temporal_data?: TemporalAnalysis;
  
  // Visual analysis
  visual_data?: VisualAnalysis;
  
  // Conceptual analysis
  conceptual_data?: ConceptualAnalysis;
  
  // Numerical analysis
  numerical_data?: NumericalAnalysis;
  
  // Emotional analysis
  emotional_data?: EmotionalAnalysis;
}

interface SpatialAnalysis {
  coordinates?: {
    latitude: number;
    longitude: number;
    accuracy_radius: number;
    confidence: number;
  };
  location_description?: string;
  terrain_features?: string[];
  distance_references?: DistanceReference[];
  spatial_relationships?: SpatialRelationship[];
}

interface TemporalAnalysis {
  time_references?: TimeReference[];
  sequence_of_events?: SequenceEvent[];
  duration_estimates?: DurationEstimate[];
  temporal_patterns?: TemporalPattern[];
  prediction_timeline?: PredictionTimeline;
}

interface VisualAnalysis {
  visual_elements?: VisualElement[];
  color_scheme?: ColorScheme;
  lighting_conditions?: LightingConditions;
  perspective?: VisualPerspective;
  scene_composition?: SceneComposition;
}

interface ProcessingMetadata {
  total_processing_time: number;  // Total time in seconds
  queue_time: number;            // Time spent in queue
  analysis_time: number;         // Actual analysis time
  models_used: string[];         // Models that were used
  data_points_processed: number;  // Number of data points
  computational_resources: ComputationalResources;
  quality_metrics: QualityMetrics;
}

interface ModelInformation {
  primary_model: string;          // Primary model used
  model_version: string;          // Model version
  ensemble_models?: string[];     // Ensemble models used
  training_data_cutoff: Date;     // Training data cutoff date
  model_accuracy: number;         // Model accuracy on validation set
  confidence_calibration: number; // Confidence calibration score
}

Analysis Model

interface Analysis {
  // Primary identification
  id: string;                    // UUID v4
  session_id: string;            // Parent session ID
  analysis_type: AnalysisType;    // Type of analysis
  
  // Status and timing
  status: AnalysisStatus;         // Current status
  created_at: Date;              // Analysis creation
  started_at?: Date;             // Analysis start
  completed_at?: Date;           // Completion time
  
  // Results and confidence
  results: AnalysisResults;       // Analysis results
  confidence_score: number;      // Confidence score (0-1)
  quality_score?: number;         // Quality assessment
  
  // Processing information
  model_used: string;            // Model that performed analysis
  model_version: string;         // Model version
  processing_parameters: Record<string, any>; // Processing params
  computational_cost: number;     // Computational cost in credits
  
  // Validation and review
  validation_results?: ValidationResults; // Validation data
  peer_reviews?: PeerReview[];    // Peer review results
  expert_review?: ExpertReview;  // Expert review if applicable
  
  // Metadata
  metadata: Record<string, any>; // Custom metadata
  tags: string[];                // Analysis tags
}

enum AnalysisStatus {
  PENDING = 'pending',
  PROCESSING = 'processing',
  COMPLETED = 'completed',
  FAILED = 'failed',
  CANCELLED = 'cancelled'
}

interface AnalysisResults {
  // Core analysis data
  primary_result: any;           // Main analysis result
  secondary_results?: any[];      // Additional results
  
  // Confidence and reliability
  confidence_breakdown: ConfidenceBreakdown;
  reliability_score: number;      // Reliability assessment
  
  // Supporting information
  methodology: string;            // Analysis methodology
  assumptions: string[];          // Key assumptions
  limitations: string[];          // Known limitations
  
  // Context and interpretation
  context: AnalysisContext;       // Analysis context
  interpretation: string;         // Interpretation of results
  implications: string[];         // Potential implications
}

interface ConfidenceBreakdown {
  overall: number;                // Overall confidence
  by_category: Record<string, number>; // Confidence by category
  by_model: Record<string, number>; // Confidence by model
  uncertainty_sources: UncertaintySource[]; // Sources of uncertainty
}

interface UncertaintySource {
  source: string;                // Source of uncertainty
  impact: number;                // Impact on confidence (0-1)
  description: string;           // Description of uncertainty
  mitigation?: string;           // Mitigation strategies
}

Billing Models

Subscription Model

interface Subscription {
  // Primary identification
  id: string;                    // UUID v4
  user_id: string;               // User UUID
  stripe_subscription_id: string; // Stripe subscription ID
  
  // Subscription details
  tier: UserTier;                // Subscription tier
  status: SubscriptionStatus;     // Current status
  plan_id: string;               // Plan identifier
  
  // Billing cycle
  current_period_start: Date;    // Current period start
  current_period_end: Date;      // Current period end
  billing_cycle: BillingCycle;   // Billing frequency
  
  // Pricing and credits
  monthly_price: number;         // Monthly price in cents
  included_credits: number;      // Credits included per period
  credit_rate: number;           // Cost per additional credit
  
  // Usage tracking
  credits_used: number;          // Credits used this period
  credits_remaining: number;     // Credits remaining
  overage_charges: number;       // Overage charges this period
  
  // Payment information
  payment_method_id: string;     // Default payment method
  last_payment_at?: Date;        // Last successful payment
  next_payment_at: Date;          // Next payment date
  
  // Metadata
  metadata: Record<string, any>; // Custom metadata
  created_at: Date;              // Subscription creation
  updated_at: Date;              // Last update
  cancelled_at?: Date;           // Cancellation timestamp
}

enum SubscriptionStatus {
  ACTIVE = 'active',
  PAST_DUE = 'past_due',
  CANCELLED = 'cancelled',
  UNPAID = 'unpaid',
  TRIALING = 'trialing'
}

enum BillingCycle {
  MONTHLY = 'monthly',
  QUARTERLY = 'quarterly',
  ANNUAL = 'annual'
}

Transaction Model

interface Transaction {
  // Primary identification
  id: string;                    // UUID v4
  user_id: string;               // User UUID
  stripe_transaction_id: string; // Stripe transaction ID
  
  // Transaction details
  type: TransactionType;         // Type of transaction
  amount: number;                // Amount in cents
  currency: string;              // Currency code (ISO 4217)
  status: TransactionStatus;      // Transaction status
  
  // Description and categorization
  description: string;           // Transaction description
  category: TransactionCategory; // Transaction category
  item_description?: string;      // Specific item description
  
  // Related entities
  subscription_id?: string;       // Related subscription
  session_id?: string;           // Related session
  invoice_id?: string;           // Related invoice
  
  // Timing
  created_at: Date;              // Transaction creation
  processed_at?: Date;           // Processing timestamp
  settled_at?: Date;             // Settlement timestamp
  
  // Financial details
  net_amount?: number;           // Net amount after fees
  fees?: number;                 // Processing fees
  tax?: number;                  // Tax amount
  refund_amount?: number;        // Refund amount if applicable
  
  // Metadata
  metadata: Record<string, any>; // Custom metadata
  notes?: string;                // Internal notes
}

enum TransactionType {
  CHARGE = 'charge',
  REFUND = 'refund',
  CREDIT_PURCHASE = 'credit_purchase',
  SUBSCRIPTION_PAYMENT = 'subscription_payment',
  ADJUSTMENT = 'adjustment'
}

enum TransactionStatus {
  PENDING = 'pending',
  PROCESSING = 'processing',
  COMPLETED = 'completed',
  FAILED = 'failed',
  CANCELLED = 'cancelled',
  REFUNDED = 'refunded'
}

enum TransactionCategory {
  SUBSCRIPTION = 'subscription',
  CREDITS = 'credits',
  USAGE_FEES = 'usage_fees',
  REFUNDS = 'refunds',
  ADJUSTMENTS = 'adjustments'
}

System Models

API Key Model

interface ApiKey {
  // Primary identification
  id: string;                    // UUID v4
  user_id: string;               // User UUID
  key_hash: string;              // Hashed API key
  key_prefix: string;            // First 8 characters for identification
  
  // Key details
  name: string;                   // Human-readable name
  description?: string;          // Optional description
  permissions: Permission[];      // Granted permissions
  
  // Usage limits
  rate_limit_per_minute?: number; // Rate limit per minute
  rate_limit_per_hour?: number;   // Rate limit per hour
  monthly_quota?: number;        // Monthly quota
  
  // Status and lifecycle
  status: ApiKeyStatus;          // Current status
  last_used_at?: Date;           // Last usage timestamp
  expires_at?: Date;             // Expiration date if applicable
  
  // Security
  ip_whitelist?: string[];       // Allowed IP addresses
  allowed_origins?: string[];    // Allowed CORS origins
  require_https: boolean;         // HTTPS requirement
  
  // Metadata
  metadata: Record<string, any>; // Custom metadata
  created_at: Date;              // Key creation
  updated_at: Date;              // Last update
  deleted_at?: Date;             // Soft delete timestamp
}

enum ApiKeyStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive',
  SUSPENDED = 'suspended',
  EXPIRED = 'expired'
}

interface Permission {
  resource: string;              // Resource identifier
  actions: string[];             // Allowed actions
  conditions?: Record<string, any>; // Access conditions
}

Webhook Model

interface Webhook {
  // Primary identification
  id: string;                    // UUID v4
  user_id: string;               // User UUID
  url: string;                   // Webhook URL
  
  // Configuration
  events: WebhookEvent[];        // Subscribed events
  secret: string;                // Webhook secret for signature
  active: boolean;               // Webhook activation status
  
  // Delivery settings
  retry_config: RetryConfig;     // Retry configuration
  timeout: number;               // Request timeout in seconds
  custom_headers?: Record<string, string>; // Custom headers
  
  // Security
  ssl_verification: boolean;     // SSL certificate verification
  ip_whitelist?: string[];       // Allowed IP addresses
  
  // Status and monitoring
  status: WebhookStatus;         // Current status
  last_delivery_at?: Date;       // Last successful delivery
  last_success_at?: Date;        // Last successful timestamp
  failure_count: number;         // Consecutive failures
  
  // Statistics
  total_deliveries: number;      // Total delivery attempts
  successful_deliveries: number; // Successful deliveries
  failed_deliveries: number;     // Failed deliveries
  
  // Metadata
  description?: string;          // Webhook description
  metadata: Record<string, any>; // Custom metadata
  created_at: Date;              // Webhook creation
  updated_at: Date;              // Last update
}

enum WebhookStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive',
  SUSPENDED = 'suspended',
  FAILED = 'failed'
}

enum WebhookEvent {
  SESSION_COMPLETED = 'session.completed',
  SESSION_FAILED = 'session.failed',
  ANALYSIS_READY = 'analysis.ready',
  USER_CREATED = 'user.created',
  BILLING_PAYMENT_SUCCEEDED = 'billing.payment_succeeded',
  BILLING_PAYMENT_FAILED = 'billing.payment_failed'
}

interface RetryConfig {
  max_attempts: number;          // Maximum retry attempts
  backoff_strategy: BackoffStrategy; // Backoff strategy
  initial_delay: number;         // Initial delay in seconds
  max_delay: number;             // Maximum delay in seconds
}

enum BackoffStrategy {
  LINEAR = 'linear',
  EXPONENTIAL = 'exponential',
  FIXED = 'fixed'
}

Webhook Delivery Model

interface WebhookDelivery {
  // Primary identification
  id: string;                    // UUID v4
  webhook_id: string;            // Parent webhook ID
  event_type: WebhookEvent;      // Event type
  
  // Request details
  url: string;                   // Delivery URL
  method: string;                // HTTP method
  headers: Record<string, string>; // Request headers
  payload: any;                  // Request payload
  
  // Response details
  status_code?: number;          // HTTP status code
  response_headers?: Record<string, string>; // Response headers
  response_body?: string;        // Response body
  
  // Timing and status
  status: DeliveryStatus;        // Delivery status
  attempt_number: number;        // Current attempt number
  created_at: Date;              // Delivery creation
  delivered_at?: Date;           // Successful delivery time
  next_retry_at?: Date;          // Next retry time
  
  // Error information
  error_message?: string;        // Error message if failed
  error_type?: string;           // Error type classification
  
  // Performance metrics
  duration_ms?: number;          // Request duration in milliseconds
  response_size_bytes?: number;  // Response size in bytes
}

enum DeliveryStatus {
  PENDING = 'pending',
  IN_PROGRESS = 'in_progress',
  SUCCEEDED = 'succeeded',
  FAILED = 'failed',
  CANCELLED = 'cancelled'
}

Database Schema

PostgreSQL Schema

-- Users table
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) UNIQUE NOT NULL,
    username VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    tier VARCHAR(50) NOT NULL DEFAULT 'basic',
    credits INTEGER NOT NULL DEFAULT 0,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    organization VARCHAR(255),
    phone VARCHAR(50),
    timezone VARCHAR(50) NOT NULL DEFAULT 'UTC',
    language VARCHAR(10) NOT NULL DEFAULT 'en',
    email_verified BOOLEAN NOT NULL DEFAULT FALSE,
    two_factor_enabled BOOLEAN NOT NULL DEFAULT FALSE,
    preferences JSONB NOT NULL DEFAULT '{}',
    notifications JSONB NOT NULL DEFAULT '{}',
    metadata JSONB NOT NULL DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    last_login TIMESTAMP WITH TIME ZONE,
    deleted_at TIMESTAMP WITH TIME ZONE
);

-- Sessions table
CREATE TABLE sessions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    cue TEXT NOT NULL,
    session_type VARCHAR(50) NOT NULL,
    status VARCHAR(50) NOT NULL DEFAULT 'pending',
    priority VARCHAR(20) NOT NULL DEFAULT 'normal',
    parameters JSONB NOT NULL DEFAULT '{}',
    confidence_score DECIMAL(5,4),
    results JSONB,
    credits_required INTEGER NOT NULL,
    credits_used INTEGER,
    processing_time INTEGER,
    metadata JSONB NOT NULL DEFAULT '{}',
    tags TEXT[] NOT NULL DEFAULT '{}',
    category VARCHAR(100),
    sensitivity VARCHAR(20) NOT NULL DEFAULT 'medium',
    quality_score DECIMAL(5,4),
    validation_status VARCHAR(50),
    reviewer_notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    started_at TIMESTAMP WITH TIME ZONE,
    completed_at TIMESTAMP WITH TIME ZONE,
    estimated_completion TIMESTAMP WITH TIME ZONE
);

-- Analyses table
CREATE TABLE analyses (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
    analysis_type VARCHAR(50) NOT NULL,
    status VARCHAR(50) NOT NULL DEFAULT 'pending',
    results JSONB NOT NULL,
    confidence_score DECIMAL(5,4) NOT NULL,
    quality_score DECIMAL(5,4),
    model_used VARCHAR(100) NOT NULL,
    model_version VARCHAR(50) NOT NULL,
    processing_parameters JSONB NOT NULL DEFAULT '{}',
    computational_cost INTEGER NOT NULL,
    validation_results JSONB,
    metadata JSONB NOT NULL DEFAULT '{}',
    tags TEXT[] NOT NULL DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    started_at TIMESTAMP WITH TIME ZONE,
    completed_at TIMESTAMP WITH TIME ZONE
);

-- API Keys table
CREATE TABLE api_keys (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    key_hash VARCHAR(255) NOT NULL UNIQUE,
    key_prefix VARCHAR(8) NOT NULL,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    permissions JSONB NOT NULL DEFAULT '[]',
    rate_limit_per_minute INTEGER,
    rate_limit_per_hour INTEGER,
    monthly_quota INTEGER,
    status VARCHAR(20) NOT NULL DEFAULT 'active',
    last_used_at TIMESTAMP WITH TIME ZONE,
    expires_at TIMESTAMP WITH TIME ZONE,
    ip_whitelist TEXT[] NOT NULL DEFAULT '{}',
    allowed_origins TEXT[] NOT NULL DEFAULT '{}',
    require_https BOOLEAN NOT NULL DEFAULT TRUE,
    metadata JSONB NOT NULL DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    deleted_at TIMESTAMP WITH TIME ZONE
);

-- Webhooks table
CREATE TABLE webhooks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    url VARCHAR(2048) NOT NULL,
    events TEXT[] NOT NULL DEFAULT '{}',
    secret VARCHAR(255) NOT NULL,
    active BOOLEAN NOT NULL DEFAULT TRUE,
    retry_config JSONB NOT NULL DEFAULT '{}',
    timeout INTEGER NOT NULL DEFAULT 30,
    custom_headers JSONB NOT NULL DEFAULT '{}',
    ssl_verification BOOLEAN NOT NULL DEFAULT TRUE,
    ip_whitelist TEXT[] NOT NULL DEFAULT '{}',
    status VARCHAR(20) NOT NULL DEFAULT 'active',
    last_delivery_at TIMESTAMP WITH TIME ZONE,
    last_success_at TIMESTAMP WITH TIME ZONE,
    failure_count INTEGER NOT NULL DEFAULT 0,
    total_deliveries INTEGER NOT NULL DEFAULT 0,
    successful_deliveries INTEGER NOT NULL DEFAULT 0,
    failed_deliveries INTEGER NOT NULL DEFAULT 0,
    description TEXT,
    metadata JSONB NOT NULL DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Webhook Deliveries table
CREATE TABLE webhook_deliveries (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    webhook_id UUID NOT NULL REFERENCES webhooks(id) ON DELETE CASCADE,
    event_type VARCHAR(100) NOT NULL,
    url VARCHAR(2048) NOT NULL,
    method VARCHAR(10) NOT NULL DEFAULT 'POST',
    headers JSONB NOT NULL DEFAULT '{}',
    payload JSONB NOT NULL,
    status_code INTEGER,
    response_headers JSONB,
    response_body TEXT,
    status VARCHAR(20) NOT NULL DEFAULT 'pending',
    attempt_number INTEGER NOT NULL DEFAULT 1,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    delivered_at TIMESTAMP WITH TIME ZONE,
    next_retry_at TIMESTAMP WITH TIME ZONE,
    error_message TEXT,
    error_type VARCHAR(100),
    duration_ms INTEGER,
    response_size_bytes INTEGER
);

-- Indexes for performance optimization
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_username ON users(username);
CREATE INDEX idx_users_tier ON users(tier);
CREATE INDEX idx_sessions_user_id ON sessions(user_id);
CREATE INDEX idx_sessions_status ON sessions(status);
CREATE INDEX idx_sessions_type ON sessions(session_type);
CREATE INDEX idx_sessions_created_at ON sessions(created_at);
CREATE INDEX idx_analyses_session_id ON analyses(session_id);
CREATE INDEX idx_analyses_status ON analyses(status);
CREATE INDEX idx_api_keys_user_id ON api_keys(user_id);
CREATE INDEX idx_api_keys_key_hash ON api_keys(key_hash);
CREATE INDEX idx_webhooks_user_id ON webhooks(user_id);
CREATE INDEX idx_webhook_deliveries_webhook_id ON webhook_deliveries(webhook_id);
CREATE INDEX idx_webhook_deliveries_status ON webhook_deliveries(status);

Redis Data Structures

session:{session_id} -> Session object (TTL: 24h)
session:{session_id}:status -> Session status (TTL: 1h)
session:{session_id}:results -> Analysis results (TTL: 7d)
session:{session_id}:queue -> Queue position (TTL: 1h)

user:{user_id} -> User profile (TTL: 1h)
user:{user_id}:permissions -> User permissions (TTL: 30m)
user:{user_id}:rate_limit -> Rate limit counter (TTL: 1m)
user:{user_id}:credits -> Credit balance (TTL: 5m)

api_key:{key_hash} -> API key info (TTL: 30m)
api_key:{key_hash}:rate_limit -> API key rate limit (TTL: 1m)

config:system -> System configuration (TTL: 5m)
models:active -> Active model list (TTL: 10m)
stats:realtime -> Real-time statistics (TTL: 30s)
queue:depth -> Current queue depths (TTL: 10s)

upload:{upload_id} -> Upload metadata (TTL: 1h)
analysis:temp:{analysis_id} -> Temporary analysis data (TTL: 2h)
webhook:retry:{delivery_id} -> Retry information (TTL: 24h)

These comprehensive data models provide the foundation for the MindPeeker platform's data architecture, ensuring consistency, scalability, and maintainability across all system components.