import { rawQuery } from '../db.js';

/**
 * Signal Logger
 * Writes generated signals to the database asynchronously.
 */

/**
 * Log a batch of signals to PostgreSQL
 * 
 * @param {Array} signals - Array of signal objects from scoringEngine
 */
export async function logSignals(signals) {
  if (!signals || signals.length === 0) return;

  try {
    // Generate a single INSERT with multiple VALUES clauses for batching
    const values = [];
    const params = [];
    let paramIdx = 1;

    for (const s of signals) {
      values.push(`($${paramIdx++}, $${paramIdx++}, $${paramIdx++}, $${paramIdx++}, $${paramIdx++}, $${paramIdx++}, $${paramIdx++}, $${paramIdx++}, $${paramIdx++})`);
      params.push(
        s.ticker,
        s.ts,            // TIMESTAMPTZ
        s.lane,
        s.score,
        s.grade,
        s.entry_price,
        JSON.stringify(s.features),
        JSON.stringify(s.regime),
        s.data_age_sec
      );
    }

    const sql = `
      INSERT INTO signals (
        ticker, ts, lane, score, grade, entry_price, features, regime, data_age_sec
      ) VALUES ${values.join(', ')}
    `;

    // Fire and forget (don't block the caller)
    rawQuery(sql, params).catch(err => {
      console.error('[signalLogger] Async insert failed:', err.message);
    });
    
  } catch (err) {
    console.error('[signalLogger] Sync setup failed:', err.message);
  }
}
