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

/**
 * Daily Analysis Query Module
 * Handles queries for daily post-mortem analysis
 */

export class DailyAnalysisQuery {
  /**
   * Get daily analysis for a specific date
   * @param {string} date - Date in YYYY-MM-DD format
   * @returns {Promise<Object>} Daily analysis data
   */
  static async getDailyAnalysis(date) {
    const { data, error } = await supabase
      .from('daily_analysis')
      .select('*')
      .eq('analysis_date', date)
      .single();
    
    if (error && error.code !== 'PGRST116') {
      throw new Error(`Database query failed: ${error.message}`);
    }
    
    return data;
  }
  
  /**
   * Get recent daily analyses
   * @param {number} limit - Number of days to retrieve
   * @returns {Promise<Array>} Daily analyses
   */
  static async getRecentAnalyses(limit = 30) {
    const { data, error } = await supabase
      .from('daily_analysis')
      .select('*')
      .order('analysis_date', { ascending: false })
      .limit(limit);
    
    if (error) {
      throw new Error(`Database query failed: ${error.message}`);
    }
    
    return data || [];
  }
  
  /**
   * Get top performers for a specific date
   * @param {string} date - Date in YYYY-MM-DD format
   * @param {number} limit - Number of top performers
   * @returns {Promise<Array>} Top performing symbols
   */
  static async getTopPerformers(date, limit = 10) {
    const { data, error } = await supabase
      .from('daily_analysis')
      .select('*')
      .eq('analysis_date', date)
      .order('final_score', { ascending: false })
      .limit(limit);
    
    if (error) {
      throw new Error(`Database query failed: ${error.message}`);
    }
    
    return data || [];
  }
  
  /**
   * Get symbol performance over time
   * @param {string} symbol - Stock symbol
   * @param {number} days - Number of days to look back
   * @returns {Promise<Array>} Historical performance data
   */
  static async getSymbolPerformance(symbol, days = 30) {
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - days);
    
    const { data, error } = await supabase
      .from('daily_analysis')
      .select('*')
      .eq('symbol', symbol.toUpperCase())
      .gte('analysis_date', startDate.toISOString().split('T')[0])
      .order('analysis_date', { ascending: true });
    
    if (error) {
      throw new Error(`Database query failed: ${error.message}`);
    }
    
    return data || [];
  }
  
  /**
   * Get analysis summary statistics
   * @param {string} date - Date in YYYY-MM-DD format
   * @returns {Promise<Object>} Summary statistics
   */
  static async getAnalysisSummary(date) {
    const { data, error } = await supabase
      .from('daily_analysis')
      .select('*')
      .eq('analysis_date', date);
    
    if (error) {
      throw new Error(`Database query failed: ${error.message}`);
    }
    
    if (!data || data.length === 0) {
      return {
        date,
        totalSymbols: 0,
        avgScore: 0,
        topScore: 0,
        winners: 0,
        losers: 0
      };
    }
    
    const scores = data.map(a => a.final_score || 0);
    const winners = data.filter(a => (a.price_change_percent || 0) > 0);
    const losers = data.filter(a => (a.price_change_percent || 0) < 0);
    
    return {
      date,
      totalSymbols: data.length,
      avgScore: scores.reduce((a, b) => a + b, 0) / scores.length,
      topScore: Math.max(...scores),
      winners: winners.length,
      losers: losers.length,
      winRate: data.length > 0 ? (winners.length / data.length) * 100 : 0
    };
  }
}

// Export a SQL query string for raw queries
// This should be replaced with your actual daily analysis SQL query
export const dailyAnalysisQuery = `
-- Daily Analysis Query
-- Replace this with your actual SQL query
SELECT * FROM daily_analysis 
WHERE analysis_date >= CURRENT_DATE - INTERVAL '30 days'
ORDER BY analysis_date DESC;
`;

