// Typeform service — ESM conversion of typeform-server/services/typeform.service.js.
// Phase 4: accepts injected ioredis client. node-redis v4 set syntax `{ EX: 300 }`
// translated to ioredis `setex(key, 300, val)`.

import axios from 'axios';

export class TypeformService {
  constructor(redis) {
    if (!redis) {
      throw new Error('TypeformService requires an ioredis client (Phase 4: injected)');
    }
    this.redis = redis;

    const token = process.env.TYPEFORM_ACCESS_TOKEN;
    if (!token) {
      console.warn('[Typeform] TYPEFORM_ACCESS_TOKEN not set — all calls will 401');
    }

    this.apiClient = axios.create({
      baseURL: 'https://api.typeform.com',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });
  }

  get _redisReady() {
    return this.redis.status === 'ready' || this.redis.status === 'connect';
  }

  async _cacheGet(key) {
    if (!this._redisReady) return null;
    try {
      const raw = await this.redis.get(key);
      return raw ? JSON.parse(raw) : null;
    } catch (err) {
      console.warn('[Typeform] cache get failed:', err.message);
      return null;
    }
  }

  async _cacheSet(key, value, ttlSec) {
    if (!this._redisReady) return;
    try {
      await this.redis.setex(key, ttlSec, JSON.stringify(value));
    } catch (err) {
      console.warn('[Typeform] cache set failed:', err.message);
    }
  }

  async getFormResponses(formId, params = {}) {
    const cacheKey = `typeform:responses:${formId}:${JSON.stringify(params)}`;
    const cached = await this._cacheGet(cacheKey);
    if (cached) return cached;

    const response = await this.apiClient.get(`/forms/${formId}/responses`, { params });
    const data = response.data;
    await this._cacheSet(cacheKey, data, 300);
    return data;
  }

  async getFormInsights(formId) {
    const cacheKey = `typeform:insights:${formId}`;
    const cached = await this._cacheGet(cacheKey);
    if (cached) return cached;

    const response = await this.apiClient.get(`/insights/${formId}/summary`);
    const data = response.data;
    await this._cacheSet(cacheKey, data, 300);
    return data;
  }

  async getFormResponsesWithFilters(formId, { since, until, pageSize = 25, ...otherParams } = {}) {
    const params = { page_size: pageSize, ...otherParams };
    if (since) params.since = new Date(since).toISOString();
    if (until) params.until = new Date(until).toISOString();
    return this.getFormResponses(formId, params);
  }
}
