/**
 * Pipeline Alert Reporting
 * 
 * Client-side utilities for reporting critical pipeline issues to system alerts.
 * Non-blocking operations that enhance monitoring without disrupting user flows.
 */

import { supabase } from '@/lib/supabaseClient';
import { handleNonCriticalError } from '@/lib/errorHandler';

/**
 * Report temp ref validation errors to system alerts
 * Called when validateTempRefs() fails in entitySubmissionHelpers
 */
export async function reportTempRefError(
  entityType: 'park' | 'ride',
  errors: string[],
  userId: string
): Promise<void> {
  try {
    await supabase.rpc('create_system_alert', {
      p_alert_type: 'temp_ref_error',
      p_severity: 'high',
      p_message: `Temp reference validation failed for ${entityType}: ${errors.join(', ')}`,
      p_metadata: {
        entity_type: entityType,
        errors,
        user_id: userId,
        timestamp: new Date().toISOString()
      }
    });
  } catch (error) {
    handleNonCriticalError(error, {
      action: 'Report temp ref error to alerts'
    });
  }
}

/**
 * Report submission queue backlog
 * Called when IndexedDB queue exceeds threshold
 */
export async function reportQueueBacklog(
  pendingCount: number,
  userId?: string
): Promise<void> {
  // Only report if backlog > 10
  if (pendingCount <= 10) return;

  try {
    await supabase.rpc('create_system_alert', {
      p_alert_type: 'submission_queue_backlog',
      p_severity: pendingCount > 50 ? 'high' : 'medium',
      p_message: `Submission queue backlog: ${pendingCount} pending submissions`,
      p_metadata: {
        pending_count: pendingCount,
        user_id: userId,
        timestamp: new Date().toISOString()
      }
    });
  } catch (error) {
    handleNonCriticalError(error, {
      action: 'Report queue backlog to alerts'
    });
  }
}

/**
 * Check queue status and report if needed
 * Called on app startup and periodically
 */
export async function checkAndReportQueueStatus(userId?: string): Promise<void> {
  try {
    const { getPendingCount } = await import('./submissionQueue');
    const pendingCount = await getPendingCount();
    await reportQueueBacklog(pendingCount, userId);
  } catch (error) {
    handleNonCriticalError(error, {
      action: 'Check queue status'
    });
  }
}

/**
 * Report rate limit violations to system alerts
 * Called when checkSubmissionRateLimit() blocks a user
 */
export async function reportRateLimitViolation(
  userId: string,
  action: string,
  retryAfter: number
): Promise<void> {
  try {
    await supabase.rpc('create_system_alert', {
      p_alert_type: 'rate_limit_violation',
      p_severity: 'medium',
      p_message: `Rate limit exceeded: ${action} (retry after ${retryAfter}s)`,
      p_metadata: {
        user_id: userId,
        action,
        retry_after_seconds: retryAfter,
        timestamp: new Date().toISOString()
      }
    });
  } catch (error) {
    handleNonCriticalError(error, {
      action: 'Report rate limit violation to alerts'
    });
  }
}

/**
 * Report ban evasion attempts to system alerts
 * Called when banned users attempt to submit content
 */
export async function reportBanEvasionAttempt(
  userId: string,
  action: string,
  username?: string
): Promise<void> {
  try {
    await supabase.rpc('create_system_alert', {
      p_alert_type: 'ban_attempt',
      p_severity: 'high',
      p_message: `Banned user attempted submission: ${action}${username ? ` (${username})` : ''}`,
      p_metadata: {
        user_id: userId,
        action,
        username: username || 'unknown',
        timestamp: new Date().toISOString()
      }
    });
  } catch (error) {
    handleNonCriticalError(error, {
      action: 'Report ban evasion attempt to alerts'
    });
  }
}
