/**
 * Debug utility for approval workflows, database operations, and real-time events.
 * Provides consistent logging with timestamps to trace system behavior.
 */

export function debugApprovalFlow(step, data) {
  const timestamp = new Date().toISOString();
  const logEntry = {
    timestamp,
    step,
    ...data
  };

  console.log(`[APPROVAL_DEBUG] ${step}:`, logEntry);
  return logEntry;
}

export function debugDatabaseInsert(table, data, result, error = null) {
  const timestamp = new Date().toISOString();
  const logEntry = {
    timestamp,
    operation: 'INSERT',
    table,
    payload: data,
    result: result ? 'SUCCESS' : 'FAILED',
    response: result,
    error
  };

  if (error) {
    console.error(`[DB_INSERT_ERROR] ${table}:`, logEntry);
  } else {
    console.log(`[DB_INSERT_SUCCESS] ${table}:`, logEntry);
  }
  return logEntry;
}

export function debugRealtimeSubscription(channel, status, payload = null) {
  const timestamp = new Date().toISOString();
  const logEntry = {
    timestamp,
    channel,
    status,
    payload
  };

  console.log(`[REALTIME_DEBUG] ${channel} - ${status}:`, logEntry);
  return logEntry;
}

export function debugUIRefresh(component, dataCount) {
  const timestamp = new Date().toISOString();
  const logEntry = {
    timestamp,
    component,
    dataCount
  };

  console.log(`[UI_REFRESH] ${component}:`, logEntry);
  return logEntry;
}

export function validateApprovalPayload(type, data) {
  const errors = [];
  
  if (type === 'task') {
    if (!data.client_id) errors.push('Missing client_id');
    if (!data.title) errors.push('Missing title');
  } else if (type === 'calendar_event') {
    if (!data.client_id) errors.push('Missing client_id');
    if (!data.start_time) errors.push('Missing start_time');
    if (!data.end_time) errors.push('Missing end_time');
    if (!data.title) errors.push('Missing title');
  }

  const result = {
    isValid: errors.length === 0,
    errors
  };

  console.log(`[VALIDATION_DEBUG] ${type}:`, result);
  return result;
}