/**
 * Hardcoded SQL templates for specific queries
 * Based on the 10 questions provided by the user
 */

class QueryTemplates {
  constructor() {
    this.templates = {
      // Q1-3: Rental price trend with context awareness
      rental_trend_monthly: (params) => ({
        sql: `
          SELECT 
            DATE_FORMAT(start_date, '%Y-%m') as month,
            AVG(annual_amount) as avg_price,
            COUNT(*) as transaction_count,
            AVG(actual_area) as avg_area
          FROM rents 
          WHERE area_en = ? 
            AND start_date >= ?
            ${params.property_filter ? 'AND prop_sub_type_en = ?' : ''}
          GROUP BY DATE_FORMAT(start_date, '%Y-%m') 
          ORDER BY month
        `,
        params: params.property_filter 
          ? [params.area, params.startDate, params.property_filter]
          : [params.area, params.startDate]
      }),

      rental_trend_weekly: (params) => ({
        sql: `
          SELECT 
            DATE_FORMAT(start_date, '%Y-%u') as week,
            AVG(annual_amount) as avg_price,
            COUNT(*) as transaction_count,
            AVG(actual_area) as avg_area
          FROM rents 
          WHERE area_en = ? 
            AND start_date >= ?
            ${params.property_filter ? 'AND prop_sub_type_en = ?' : ''}
          GROUP BY DATE_FORMAT(start_date, '%Y-%u') 
          ORDER BY week
        `,
        params: params.property_filter 
          ? [params.area, params.startDate, params.property_filter]
          : [params.area, params.startDate]
      }),

      // Project-specific brief (with project name)
      project_specific_summary: (params) => ({
        sql: `
          SELECT 
            '1. Total Transactions' as metric_name,
            COUNT(*) as metric_value,
            'Transaction Count' as metric_label
          FROM transactions
          WHERE project_en = ?
          UNION ALL
          SELECT 
            '2. Total Transaction Value' as metric_name,
            SUM(trans_value) as metric_value,
            'AED Value' as metric_label
          FROM transactions
          WHERE project_en = ?
          UNION ALL
          SELECT 
            '3. Average Transaction Value' as metric_name,
            AVG(trans_value) as metric_value,
            'AED Average' as metric_label
          FROM transactions
          WHERE project_en = ?
          UNION ALL
          SELECT 
            '4. Off-Plan Transactions' as metric_name,
            COUNT(*) as metric_value,
            'Transaction Count' as metric_label
          FROM transactions
          WHERE project_en = ? AND is_offplan_en = 'off-plan'
          UNION ALL
          SELECT 
            '5. Ready Properties' as metric_name,
            COUNT(*) as metric_value,
            'Transaction Count' as metric_label
          FROM transactions
          WHERE project_en = ? AND is_offplan_en = 'ready'
          UNION ALL
          SELECT 
            '6. Residential Transactions' as metric_name,
            COUNT(*) as metric_value,
            'Transaction Count' as metric_label
          FROM transactions
          WHERE project_en = ? AND usage_en = 'residential'
          UNION ALL
          SELECT 
            '7. Average Area' as metric_name,
            AVG(actual_area) as metric_value,
            'Square Feet' as metric_label
          FROM transactions
          WHERE project_en = ?
          UNION ALL
          SELECT 
            '8. Average Buyers per Transaction' as metric_name,
            AVG(total_buyer) as metric_value,
            'Buyer Count' as metric_label
          FROM transactions
          WHERE project_en = ?
          UNION ALL
          SELECT 
            '9. First Transaction Date' as metric_name,
            MIN(instance_date) as metric_value,
            'Date' as metric_label
          FROM transactions
          WHERE project_en = ?
          UNION ALL
          SELECT 
            '10. Latest Transaction Date' as metric_name,
            MAX(instance_date) as metric_value,
            'Date' as metric_label
          FROM transactions
          WHERE project_en = ?
        `,
        params: Array(10).fill(params.projectName)
      }),

      // General project transaction summary (no specific project)
      project_transaction_summary: (params) => ({
        sql: `
          SELECT 
            '1. Total Transactions' as metric_name,
            COUNT(*) as metric_value,
            'Transaction Count' as metric_label
          FROM transactions
          WHERE project_en IS NOT NULL
          UNION ALL
          SELECT 
            '2. Total Transaction Value' as metric_name,
            SUM(trans_value) as metric_value,
            'AED Value' as metric_label
          FROM transactions
          WHERE project_en IS NOT NULL
          UNION ALL
          SELECT 
            '3. Average Transaction Value' as metric_name,
            AVG(trans_value) as metric_value,
            'AED Average' as metric_label
          FROM transactions
          WHERE project_en IS NOT NULL
          UNION ALL
          SELECT 
            '4. Unique Projects' as metric_name,
            COUNT(DISTINCT project_en) as metric_value,
            'Project Count' as metric_label
          FROM transactions
          WHERE project_en IS NOT NULL
          UNION ALL
          SELECT 
            '5. Off-Plan Transactions' as metric_name,
            COUNT(*) as metric_value,
            'Transaction Count' as metric_label
          FROM transactions
          WHERE project_en IS NOT NULL AND is_offplan_en = 'off-plan'
          UNION ALL
          SELECT 
            '6. Ready Properties' as metric_name,
            COUNT(*) as metric_value,
            'Transaction Count' as metric_label
          FROM transactions
          WHERE project_en IS NOT NULL AND is_offplan_en = 'ready'
          UNION ALL
          SELECT 
            '7. Residential Transactions' as metric_name,
            COUNT(*) as metric_value,
            'Transaction Count' as metric_label
          FROM transactions
          WHERE project_en IS NOT NULL AND usage_en = 'residential'
          UNION ALL
          SELECT 
            '8. Average Area' as metric_name,
            AVG(actual_area) as metric_value,
            'Square Feet' as metric_label
          FROM transactions
          WHERE project_en IS NOT NULL
          UNION ALL
          SELECT 
            '9. Unique Areas' as metric_name,
            COUNT(DISTINCT area_en) as metric_value,
            'Area Count' as metric_label
          FROM transactions
          WHERE project_en IS NOT NULL
          UNION ALL
          SELECT 
            '10. Average Buyers per Transaction' as metric_name,
            AVG(total_buyer) as metric_value,
            'Buyer Count' as metric_label
          FROM transactions
          WHERE project_en IS NOT NULL
        `,
        params: []
      }),

      // Q5: List of fast moving projects
      fast_moving_projects: (params) => ({
        sql: `
          SELECT 
            project_en,
            area_en,
            COUNT(*) as transaction_count,
            AVG(trans_value) as avg_value,
            SUM(trans_value) as total_value,
            MIN(instance_date) as first_transaction,
            MAX(instance_date) as last_transaction
          FROM transactions 
          WHERE project_en IS NOT NULL 
            AND instance_date >= ?
          GROUP BY project_en, area_en
          HAVING transaction_count >= 5
          ORDER BY transaction_count DESC
          LIMIT 20
        `,
        params: [params.startDate]
      }),

      // Q6: Areas with uptick in off-plan projects
      offplan_uptick_areas: (params) => ({
        sql: `
          SELECT 
            area_en,
            COUNT(*) as total_offplan_transactions,
            AVG(trans_value) as avg_value,
            COUNT(DISTINCT project_en) as unique_projects
          FROM transactions 
          WHERE is_offplan_en = 'off-plan' 
            AND instance_date >= ?
            AND area_en IS NOT NULL
          GROUP BY area_en
          ORDER BY total_offplan_transactions DESC
          LIMIT 10
        `,
        params: [params.startDate]
      }),

      // Q7: Areas with more rental transactions
      rental_transaction_areas: (params) => ({
        sql: `
          SELECT 
            area_en,
            COUNT(*) as rental_count,
            AVG(annual_amount) as avg_rental_price,
            AVG(actual_area) as avg_area,
            SUM(annual_amount) as total_rental_value
          FROM rents 
          WHERE start_date >= ?
          GROUP BY area_en
          ORDER BY rental_count DESC
          LIMIT 10
        `,
        params: [params.startDate]
      }),

      // Q8: Top 5 areas for Commercial leasing
      commercial_leasing_areas: (params) => {
        const limit = params.topCount || 5;
        return {
          sql: `
            SELECT 
              area_en,
              COUNT(*) as commercial_count,
              AVG(annual_amount) as avg_commercial_rent,
              AVG(actual_area) as avg_area,
              COUNT(DISTINCT prop_sub_type_en) as property_types
            FROM rents 
            WHERE usage_en = 'commercial' 
              AND start_date >= ?
            GROUP BY area_en
            ORDER BY commercial_count DESC, avg_commercial_rent DESC
            LIMIT ${limit}
          `,
          params: [params.startDate]
        };
      },

      // Q9: Top 5 areas for Residential leasing
      residential_leasing_areas: (params) => {
        const limit = params.topCount || 5;
        return {
          sql: `
            SELECT 
              area_en,
              COUNT(*) as residential_count,
              AVG(annual_amount) as avg_residential_rent,
              AVG(actual_area) as avg_area,
              COUNT(DISTINCT rooms) as room_types
            FROM rents 
            WHERE usage_en = 'residential' 
              AND start_date >= ?
            GROUP BY area_en
            ORDER BY residential_count DESC, avg_residential_rent DESC
            LIMIT ${limit}
          `,
          params: [params.startDate]
        };
      },

      // Q10: Avg price of 3BHK apartment by area (monthly grouping, top 5)
      bhk_apartment_price: (params) => ({
        sql: `
          WITH monthly_avg AS (
            SELECT 
              DATE_FORMAT(start_date, '%Y-%m') AS month,
              area_en,
              AVG(annual_amount) AS avg_price,
              COUNT(*) AS transaction_count,
              AVG(actual_area) AS avg_area
            FROM rents 
            WHERE rooms = ? 
              AND (prop_sub_type_en = 'flat' OR prop_sub_type_en = 'villa')
              AND start_date >= ?
              AND area_en IS NOT NULL
            GROUP BY month, area_en
            HAVING transaction_count >= 1
          ),
          ranked_areas AS (
            SELECT 
              month,
              area_en,
              avg_price,
              transaction_count,
              ROW_NUMBER() OVER (PARTITION BY month ORDER BY avg_price DESC) AS rn
            FROM monthly_avg
          )
          SELECT 
            month,
            area_en,
            ROUND(avg_price, 2) AS avg_price,
            transaction_count
          FROM ranked_areas
          WHERE rn <= 5
          ORDER BY month DESC, avg_price DESC
        `,
        params: [params.roomType, params.startDate]
      }),

      // Context-aware query with refinements
      context_aware_query: (params) => {
        let sql = `
          SELECT 
        `;
        
        // Determine grouping
        if (params.grouping === 'weekly') {
          sql += `DATE_FORMAT(start_date, '%Y-%u') as period,`;
        } else {
          sql += `DATE_FORMAT(start_date, '%Y-%m') as period,`;
        }
        
        sql += `
            AVG(annual_amount) as avg_price,
            COUNT(*) as transaction_count,
            AVG(actual_area) as avg_area
          FROM rents 
          WHERE area_en = ? 
            AND start_date >= ?
        `;
        
        const sqlParams = [params.area, params.startDate];
        
        // Add property filter
        if (params.property_filter) {
          sql += ' AND prop_sub_type_en = ?';
          sqlParams.push(params.property_filter);
        }
        
        // Add room filter
        if (params.room_filter) {
          sql += ' AND rooms = ?';
          sqlParams.push(params.room_filter);
        }
        
        // Add grouping
        if (params.grouping === 'weekly') {
          sql += ' GROUP BY DATE_FORMAT(start_date, \'%Y-%u\')';
        } else {
          sql += ' GROUP BY DATE_FORMAT(start_date, \'%Y-%m\')';
        }
        
        sql += ' ORDER BY period';
        
        return {
          sql,
          params: sqlParams
        };
      }
    };
  }

  /**
   * Get template for a specific query type
   */
  getTemplate(templateName, params) {
    if (!this.templates[templateName]) {
      throw new Error(`Template ${templateName} not found`);
    }
    
    return this.templates[templateName](params);
  }

  /**
   * Detect which template to use based on query
   */
  detectTemplate(parsedQuery) {
    const query = parsedQuery.original_query.toLowerCase();
    const { intent, areas, time_period } = parsedQuery;
    
    // BHK apartment price - check this FIRST to avoid conflicts with rental trend
    if (query.includes('3bhk') || query.includes('bhk')) {
      return 'bhk_apartment_price';
    }
    
    // Rental trend queries - use intent and context instead of just keywords
    if (intent === 'trend' && areas && areas.length > 0 && time_period) {
      if (parsedQuery.refinements?.grouping === 'weekly') {
        return 'rental_trend_weekly';
      }
      return 'rental_trend_monthly';
    }
    
    // Also check for explicit rental keywords as fallback
    if (query.includes('rental') && query.includes('trend')) {
      if (parsedQuery.refinements?.grouping === 'weekly') {
        return 'rental_trend_weekly';
      }
      return 'rental_trend_monthly';
    }
    
    // Project-specific summary (with project name)
    if ((query.includes('brief') || query.includes('summary')) && query.includes('project') && parsedQuery.projectName) {
      return 'project_specific_summary';
    }
    
    // General project summary
    if ((query.includes('brief') || query.includes('summary')) && query.includes('project')) {
      return 'project_transaction_summary';
    }
    
    // Fast moving projects
    if (query.includes('fast moving') && query.includes('project')) {
      return 'fast_moving_projects';
    }
    
    // Off-plan uptick - check for various phrasings
    if ((query.includes('uptick') || query.includes('increase') || query.includes('growth') || query.includes('surge') || query.includes('rise')) && 
        (query.includes('off-plan') || query.includes('offplan'))) {
      return 'offplan_uptick_areas';
    }
    
    // Rental transactions by area - check for various phrasings
    if ((query.includes('area') || query.includes('areas') || query.includes('which area')) && 
        (query.includes('rental transaction') || query.includes('rental transactions') || 
         (query.includes('rental') && query.includes('transaction')) || 
         (query.includes('more rental') && query.includes('transaction')) ||
         (query.includes('most rental') && query.includes('transaction')))) {
      return 'rental_transaction_areas';
    }
    
    // Commercial leasing
    if (query.includes('commercial') && query.includes('leasing')) {
      return 'commercial_leasing_areas';
    }
    
    // Residential leasing
    if (query.includes('residential') && query.includes('leasing')) {
      return 'residential_leasing_areas';
    }
    
    // General summary queries
    if (intent === 'summary' && areas && areas.length > 0) {
      return 'project_transaction_summary';
    }
    
    // Context-aware
    if (parsedQuery.isContextual) {
      return 'context_aware_query';
    }
    
    return null;
  }
}

module.exports = QueryTemplates;
