import { ToolingError } from '../../../../../../types'
import { withRetry, createHttpError, DEFAULT_RETRY_POLICY } from '../../../../../../../../../platform/resilience'
import type { ExecutionContext } from '../../../../../../../base/types'

interface InstantlyCredentials {
  apiKey: string
}

export interface GetStepAnalyticsParams {
  campaign_id: string
  start_date?: string
  end_date?: string
}

export interface StepAnalyticsEntry {
  step: string | null
  variant: string | null
  sent: number
  opened: number
  unique_opened: number
  replies: number
  unique_replies: number
}

export interface GetStepAnalyticsResult {
  steps: StepAnalyticsEntry[]
}

const INSTANTLY_API_BASE = 'https://api.instantly.ai/api/v2'

/**
 * Get per-step analytics for an Instantly campaign
 *
 * Retrieves a breakdown of analytics by campaign step and variant.
 * Useful for understanding which steps and subject lines perform best
 * within a multi-step sequence.
 *
 * @param credentials - Instantly API key
 * @param params - Campaign ID to fetch step analytics for
 * @param context - Execution context for logging
 * @returns Per-step, per-variant engagement metrics
 */
export async function getStepAnalytics(
  credentials: InstantlyCredentials,
  params: GetStepAnalyticsParams,
  context?: ExecutionContext
): Promise<GetStepAnalyticsResult> {
  const { apiKey } = credentials
  const { campaign_id, start_date, end_date } = params

  // Validation
  if (!campaign_id) {
    throw new ToolingError('validation_error', 'Missing required parameter: campaign_id', {
      integration: 'instantly',
      method: 'getStepAnalytics'
    })
  }

  const queryParams = new URLSearchParams()
  queryParams.set('campaign_id', campaign_id)
  if (start_date) queryParams.set('start_date', start_date)
  if (end_date) queryParams.set('end_date', end_date)

  const stepAnalyticsUrl = `${INSTANTLY_API_BASE}/campaigns/analytics/steps?${queryParams.toString()}`

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Fetching step analytics: campaign_id=${campaign_id} executionId=${context.executionId}`
    )
  }

  const response = await withRetry(async () => {
    const res = await fetch(stepAnalyticsUrl, {
      headers: {
        Authorization: `Bearer ${apiKey}`
      }
    })

    if (!res.ok) {
      throw await createHttpError(res, {
        integration: 'instantly',
        method: 'getStepAnalytics',
        organizationId: context?.organizationId
      })
    }

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  const rawData = response.data ?? response
  const steps: StepAnalyticsEntry[] = Array.isArray(rawData) ? rawData : rawData?.steps || []

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Step analytics fetched: campaign_id=${campaign_id} step_count=${steps.length} executionId=${context.executionId}`
    )
  }

  return {
    steps
  }
}
