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

class GorgiasService {
  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));
    
    // Create base64 encoded auth string
    const auth = Buffer.from(`${process.env.GORGIAS_API_USERNAME}:${process.env.GORGIAS_API_KEY}`).toString('base64');
    
    this.apiClient = axios.create({
      baseURL: `https://${process.env.GORGIAS_DOMAIN}.gorgias.com/api`,
      headers: {
        'Authorization': `Basic ${auth}`,
        'Content-Type': 'application/json'
      }
    });
  }

  async getStatistics(name, filters = {}) {
    const cacheKey = `gorgias:stats:${name}:${JSON.stringify(filters)}`;
    
    try {
      // Try Redis first
      const cachedData = await this.redis.get(cacheKey);
      if (cachedData) {
        console.log(`Statistics ${name} found in Redis cache`);
        return JSON.parse(cachedData);
      }

      console.log(`Fetching ${name} statistics with filters:`, filters);

      // Convert dates to UTC midnight if not already set
      if (!filters.start_datetime || !filters.end_datetime) {
        const start = new Date(filters.start_datetime || filters.start_date);
        start.setUTCHours(0, 0, 0, 0);
        const end = new Date(filters.end_datetime || filters.end_date);
        end.setUTCHours(23, 59, 59, 999);

        filters = {
          ...filters,
          start_datetime: start.toISOString(),
          end_datetime: end.toISOString()
        };
      }

      // Fetch from API
      const response = await this.apiClient.post(`/stats/${name}`, filters);
      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 in getStatistics for ${name}:`, {
        error: error.message,
        filters,
        response: error.response?.data
      });
      throw error;
    }
  }

  async getTickets(params = {}) {
    const cacheKey = `gorgias:tickets:${JSON.stringify(params)}`;
    
    try {
      // Try Redis first
      const cachedData = await this.redis.get(cacheKey);
      if (cachedData) {
        console.log('Tickets found in Redis cache');
        return JSON.parse(cachedData);
      }

      // Convert dates to UTC midnight
      const formattedParams = { ...params };
      if (params.start_date) {
        const start = new Date(params.start_date);
        start.setUTCHours(0, 0, 0, 0);
        formattedParams.start_datetime = start.toISOString();
        delete formattedParams.start_date;
      }
      if (params.end_date) {
        const end = new Date(params.end_date);
        end.setUTCHours(23, 59, 59, 999);
        formattedParams.end_datetime = end.toISOString();
        delete formattedParams.end_date;
      }

      // Fetch from API
      const response = await this.apiClient.get('/tickets', { params: formattedParams });
      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 tickets:', {
        error: error.message,
        params,
        response: error.response?.data
      });
      throw error;
    }
  }
}

module.exports = new GorgiasService(); 