import pool from '../db';
import { assessPlayerPropClvFit, normalizeClvPropStat } from './player-prop-clv-profile';

export async function recordClvPick(params: {
  eventId: string;
  league: string;
  pickType: string;
  direction: string;
  recLine: number | null;
  recOdds: number | null;
  playerName?: string | null;
  propStat?: string | null;
  modelConfidence?: number | null;
  stormTier?: number | null;
}): Promise<void> {
  if (params.recLine == null) return;

  const normalizedDirection = (params.direction || '').trim().toLowerCase();
  const normalizedPlayerName = (params.playerName || '').trim() || null;
  const normalizedPropStat = normalizeClvPropStat(params.propStat, params.league) || null;

  if (params.pickType === 'player_prop') {
    if (!normalizedPlayerName || !normalizedPropStat) return;
    if (normalizedDirection !== 'over' && normalizedDirection !== 'under') return;
  }

  try {
    const existing = await pool.query(
      `SELECT id
       FROM rm_pick_clv
       WHERE event_id = $1
         AND pick_type = $2
         AND direction = $3
         AND COALESCE(player_name, '') = COALESCE($4, '')
         AND COALESCE(prop_stat, '') = COALESCE($5, '')
       LIMIT 1`,
      [
        params.eventId,
        params.pickType,
        normalizedDirection || null,
        normalizedPlayerName,
        normalizedPropStat,
      ],
    );
    if (existing.rows.length > 0) return;

    // Determine v2 eligibility based on backtest-proven filters
    const v2Eligible = params.pickType === 'player_prop'
      ? assessPlayerPropClvFit({
          league: params.league,
          normalizedStatType: normalizedPropStat,
          recommendation: normalizedDirection,
          confidenceFactor: params.modelConfidence ?? null,
          odds: params.recOdds ?? null,
          marketLine: params.recLine ?? null,
        }).eligible
      : true;

    await pool.query(
      `INSERT INTO rm_pick_clv (event_id, league, pick_type, direction, rec_line, rec_odds, player_name, prop_stat, model_confidence, storm_tier, v2_eligible)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
      [
        params.eventId,
        params.league,
        params.pickType,
        normalizedDirection || null,
        params.recLine,
        params.recOdds != null ? Math.round(params.recOdds) : null,
        normalizedPlayerName,
        normalizedPropStat,
        params.modelConfidence ?? null,
        params.stormTier ?? null,
        v2Eligible,
      ],
    );
  } catch (err) {
    console.error('CLV pick recording error:', err);
  }
}
