import pool from '../db';

export async function fetchInsightSourceData(params: {
  homeTeam: string;
  awayTeam: string;
  league: string;
}): Promise<{ sharpMoves: any[]; lineMovements: any[] }> {
  try {
    const sharpMoves = await pool.query(
      `SELECT market, "moveType", "lineFrom", "lineTo", "lineChange", "oddsFrom", "oddsTo",
              "moveDetectedAt", "minutesBetweenSnapshots", "moveVelocity", "isReverseLine",
              "isSteamMove", bookmaker
       FROM "SharpMove"
       WHERE league = $1
         AND ("homeTeam" ILIKE $2 OR "awayTeam" ILIKE $2 OR "homeTeam" ILIKE $3 OR "awayTeam" ILIKE $3)
       ORDER BY "moveDetectedAt" DESC
       LIMIT 20`,
      [params.league, `%${params.homeTeam}%`, `%${params.awayTeam}%`],
    ).catch(() => ({ rows: [] as any[] }));

    const lineMovements = await pool.query(
      `SELECT "marketType", "openLine", "currentLine", "lineMovement", "movementDirection",
              "openOdds", "currentOdds", "publicPctHome", "publicPctAway",
              "sharpAction", "steamMove", "reverseLineMove", "consensusPlay", "recordedAt"
       FROM "LineMovement"
       WHERE league = $1
         AND ("homeTeam" ILIKE $2 OR "awayTeam" ILIKE $2 OR "homeTeam" ILIKE $3 OR "awayTeam" ILIKE $3)
       ORDER BY "recordedAt" DESC
       LIMIT 20`,
      [params.league, `%${params.homeTeam}%`, `%${params.awayTeam}%`],
    ).catch(() => ({ rows: [] as any[] }));

    return {
      sharpMoves: sharpMoves.rows,
      lineMovements: lineMovements.rows,
    };
  } catch (err) {
    console.error('Insight source data fetch error:', err);
    return { sharpMoves: [], lineMovements: [] };
  }
}
