-- Migration: Add Method Rotation System
-- Version: 2025-07-24-001
-- Description: Adds complete method rotation infrastructure for tracking and managing
--              registration/login method strategies across all platforms

-- Method strategies table - stores configuration and performance data for each method
CREATE TABLE IF NOT EXISTS method_strategies (
    id TEXT PRIMARY KEY,
    platform TEXT NOT NULL,
    method_name TEXT NOT NULL,
    priority INTEGER NOT NULL DEFAULT 5,
    success_rate REAL DEFAULT 0.0,
    failure_rate REAL DEFAULT 0.0,
    last_success TIMESTAMP,
    last_failure TIMESTAMP,
    cooldown_period INTEGER DEFAULT 0, -- seconds
    max_daily_attempts INTEGER DEFAULT 10,
    risk_level TEXT DEFAULT 'MEDIUM', -- LOW, MEDIUM, HIGH
    is_active BOOLEAN DEFAULT 1,
    configuration TEXT, -- JSON configuration for method-specific settings
    tags TEXT, -- JSON array for method categorization
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(platform, method_name)
);

-- Rotation sessions table - tracks active rotation sessions
CREATE TABLE IF NOT EXISTS rotation_sessions (
    id TEXT PRIMARY KEY,
    platform TEXT NOT NULL,
    account_id TEXT,
    current_method TEXT NOT NULL,
    attempted_methods TEXT, -- JSON array of attempted method names
    session_start TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    last_rotation TIMESTAMP,
    rotation_count INTEGER DEFAULT 0,
    success_count INTEGER DEFAULT 0,
    failure_count INTEGER DEFAULT 0,
    is_active BOOLEAN DEFAULT 1,
    rotation_reason TEXT,
    fingerprint_id TEXT,
    session_metadata TEXT, -- JSON for additional session data
    FOREIGN KEY (account_id) REFERENCES accounts(id),
    FOREIGN KEY (fingerprint_id) REFERENCES browser_fingerprints(id)
);

-- Rotation events table - detailed event logging for all rotation activities
CREATE TABLE IF NOT EXISTS rotation_events (
    id TEXT PRIMARY KEY,
    session_id TEXT NOT NULL,
    method_name TEXT NOT NULL,
    event_type TEXT NOT NULL, -- SUCCESS, FAILURE, ROTATION, COOLDOWN, CONFIG_CHANGE
    timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    details TEXT, -- JSON event-specific details
    error_message TEXT,
    performance_metrics TEXT, -- JSON: execution_time, memory_usage, etc.
    correlation_id TEXT, -- For linking related events
    FOREIGN KEY (session_id) REFERENCES rotation_sessions(id)
);

-- Method performance analytics table - aggregated daily performance data
CREATE TABLE IF NOT EXISTS method_performance_analytics (
    id TEXT PRIMARY KEY,
    platform TEXT NOT NULL,
    method_name TEXT NOT NULL,
    date DATE NOT NULL,
    total_attempts INTEGER DEFAULT 0,
    successful_attempts INTEGER DEFAULT 0,
    failed_attempts INTEGER DEFAULT 0,
    avg_execution_time REAL DEFAULT 0.0,
    avg_success_rate REAL DEFAULT 0.0,
    peak_usage_hour INTEGER, -- 0-23 hour when most used
    error_categories TEXT, -- JSON: categorized error types and counts
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(platform, method_name, date)
);

-- Method cooldowns table - tracks temporary method restrictions
CREATE TABLE IF NOT EXISTS method_cooldowns (
    id TEXT PRIMARY KEY,
    platform TEXT NOT NULL,
    method_name TEXT NOT NULL,
    cooldown_until TIMESTAMP NOT NULL,
    reason TEXT NOT NULL,
    applied_by TEXT DEFAULT 'system',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(platform, method_name)
);

-- Platform method states table - stores platform-specific rotation state
CREATE TABLE IF NOT EXISTS platform_method_states (
    id TEXT PRIMARY KEY,
    platform TEXT NOT NULL,
    last_successful_method TEXT,
    last_successful_at TIMESTAMP,
    preferred_methods TEXT, -- JSON array of method names in preference order
    blocked_methods TEXT, -- JSON array of temporarily blocked methods
    daily_attempt_counts TEXT, -- JSON: {"email": 3, "phone": 1}
    reset_date DATE, -- When daily counts reset
    rotation_strategy TEXT DEFAULT 'adaptive', -- sequential, random, adaptive, smart
    emergency_mode BOOLEAN DEFAULT 0,
    metadata TEXT, -- JSON: additional platform-specific state
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(platform)
);

-- Indexes for performance optimization
CREATE INDEX IF NOT EXISTS idx_method_strategies_platform ON method_strategies(platform);
CREATE INDEX IF NOT EXISTS idx_method_strategies_active ON method_strategies(platform, is_active);
CREATE INDEX IF NOT EXISTS idx_method_strategies_priority ON method_strategies(platform, priority DESC, success_rate DESC);

CREATE INDEX IF NOT EXISTS idx_rotation_sessions_platform ON rotation_sessions(platform);
CREATE INDEX IF NOT EXISTS idx_rotation_sessions_active ON rotation_sessions(platform, is_active);
CREATE INDEX IF NOT EXISTS idx_rotation_sessions_account ON rotation_sessions(account_id);

CREATE INDEX IF NOT EXISTS idx_rotation_events_session ON rotation_events(session_id);
CREATE INDEX IF NOT EXISTS idx_rotation_events_timestamp ON rotation_events(timestamp);
CREATE INDEX IF NOT EXISTS idx_rotation_events_method ON rotation_events(method_name);

CREATE INDEX IF NOT EXISTS idx_method_performance_platform_date ON method_performance_analytics(platform, date);
CREATE INDEX IF NOT EXISTS idx_method_performance_method ON method_performance_analytics(method_name);

CREATE INDEX IF NOT EXISTS idx_method_cooldowns_platform_method ON method_cooldowns(platform, method_name);
CREATE INDEX IF NOT EXISTS idx_method_cooldowns_until ON method_cooldowns(cooldown_until);

CREATE INDEX IF NOT EXISTS idx_platform_method_states_platform ON platform_method_states(platform);

-- Insert default method strategies for existing platforms
INSERT OR IGNORE INTO method_strategies (id, platform, method_name, priority, max_daily_attempts, cooldown_period, risk_level, configuration, tags) VALUES
-- Instagram methods
('instagram_email', 'instagram', 'email', 8, 20, 300, 'LOW', '{"email_domain": "z5m7q9dk3ah2v1plx6ju.com", "require_phone_verification": false, "auto_verify_email": true}', '["primary", "reliable"]'),
('instagram_phone', 'instagram', 'phone', 6, 10, 600, 'MEDIUM', '{"require_email_backup": true, "phone_verification_timeout": 300}', '["secondary", "verification"]'),
('instagram_social', 'instagram', 'social_login', 4, 5, 1800, 'HIGH', '{"supported_providers": ["facebook"], "fallback_to_email": true}', '["alternative", "high_risk"]'),

-- TikTok methods
('tiktok_email', 'tiktok', 'email', 8, 25, 240, 'LOW', '{"email_domain": "z5m7q9dk3ah2v1plx6ju.com", "require_phone_verification": false}', '["primary", "reliable"]'),
('tiktok_phone', 'tiktok', 'phone', 7, 15, 480, 'MEDIUM', '{"require_email_backup": false, "phone_verification_timeout": 180}', '["secondary", "fast"]'),

-- X (Twitter) methods
('x_email', 'x', 'email', 8, 15, 360, 'LOW', '{"email_domain": "z5m7q9dk3ah2v1plx6ju.com", "require_phone_verification": true}', '["primary", "stable"]'),
('x_phone', 'x', 'phone', 6, 8, 720, 'MEDIUM', '{"require_email_backup": true, "phone_verification_timeout": 300}', '["secondary", "verification"]'),

-- Gmail methods
('gmail_standard', 'gmail', 'standard_registration', 9, 30, 180, 'LOW', '{"recovery_email": false, "recovery_phone": false}', '["primary", "google"]'),
('gmail_recovery', 'gmail', 'recovery_registration', 7, 10, 600, 'MEDIUM', '{"recovery_email": true, "recovery_phone": false}', '["secondary", "secure"]);

-- Insert default platform method states
INSERT OR IGNORE INTO platform_method_states (id, platform, preferred_methods, rotation_strategy, reset_date) VALUES
('state_instagram', 'instagram', '["email", "phone", "social_login"]', 'adaptive', DATE('now')),
('state_tiktok', 'tiktok', '["email", "phone"]', 'adaptive', DATE('now')),
('state_x', 'x', '["email", "phone"]', 'adaptive', DATE('now')),
('state_gmail', 'gmail', '["standard_registration", "recovery_registration"]', 'adaptive', DATE('now'));

-- Migration completed successfully
INSERT OR IGNORE INTO schema_migrations (version, description, applied_at) VALUES 
('2025-07-24-001', 'Add Method Rotation System', CURRENT_TIMESTAMP);