const axios = require('axios');
const { createClient } = require('redis');

class TypeformService {
  constructor() {
    this.redis = createClient({
      url: process.env.REDIS_URL
    });
    
    this.redis.on('error', err => console.error('Redis Client Error:', err));
    this.redis.connect().catch(err => console.error('Redis connection error:', err));
    
    const token = process.env.TYPEFORM_ACCESS_TOKEN;
    console.log('Initializing Typeform client with token:', token ? `${token.slice(0, 10)}...` : 'missing');
    
    this.apiClient = axios.create({
      baseURL: 'https://api.typeform.com',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });

    // Test the token
    this.testConnection();
  }

  async testConnection() {
    try {
      const response = await this.apiClient.get('/forms');
      console.log('Typeform connection test successful:', {
        status: response.status,
        headers: response.headers,
      });
    } catch (error) {
      console.error('Typeform connection test failed:', {
        error: error.message,
        response: error.response?.data,
        status: error.response?.status,
      });
    }
  }

  async getFormResponses(formId, params = {}) {
    const cacheKey = `typeform:responses:${formId}:${JSON.stringify(params)}`;
    
    try {
      // Try Redis first
      const cachedData = await this.redis.get(cacheKey);
      if (cachedData) {
        console.log(`Form responses for ${formId} found in Redis cache`);
        return JSON.parse(cachedData);
      }

      // Fetch from API
      const response = await this.apiClient.get(`/forms/${formId}/responses`, { params });
      const data = response.data;

      // Save to Redis with 5 minute expiry
      await this.redis.set(cacheKey, JSON.stringify(data), {
        EX: 300 // 5 minutes
      });

      return data;
    } catch (error) {
      console.error(`Error fetching form responses for ${formId}:`, {
        error: error.message,
        params,
        response: error.response?.data
      });
      throw error;
    }
  }

  async getFormInsights(formId) {
    const cacheKey = `typeform:insights:${formId}`;
    
    try {
      // Try Redis first
      const cachedData = await this.redis.get(cacheKey);
      if (cachedData) {
        console.log(`Form insights for ${formId} found in Redis cache`);
        return JSON.parse(cachedData);
      }

      // Log the request details
      console.log(`Fetching insights for form ${formId}...`, {
        url: `/insights/${formId}/summary`,
        headers: this.apiClient.defaults.headers
      });

      // Fetch from API
      const response = await this.apiClient.get(`/insights/${formId}/summary`);
      console.log('Typeform insights response:', {
        status: response.status,
        headers: response.headers,
        data: response.data
      });
      const data = response.data;

      // Save to Redis with 5 minute expiry
      await this.redis.set(cacheKey, JSON.stringify(data), {
        EX: 300 // 5 minutes
      });

      return data;
    } catch (error) {
      console.error(`Error fetching form insights for ${formId}:`, {
        error: error.message,
        response: error.response?.data,
        status: error.response?.status,
        headers: error.response?.headers,
        requestUrl: `/insights/${formId}/summary`,
        requestHeaders: this.apiClient.defaults.headers
      });
      throw error;
    }
  }

  async getFormResponsesWithFilters(formId, { since, until, pageSize = 25, ...otherParams } = {}) {
    try {
      const params = {
        page_size: pageSize,
        ...otherParams
      };

      if (since) {
        params.since = new Date(since).toISOString();
      }
      if (until) {
        params.until = new Date(until).toISOString();
      }

      return await this.getFormResponses(formId, params);
    } catch (error) {
      console.error('Error in getFormResponsesWithFilters:', error);
      throw error;
    }
  }
}

module.exports = new TypeformService(); 