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

interface InstantlyCredentials {
  apiKey: string
}

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

export interface GetDailyCampaignAnalyticsResult {
  data: Array<{
    date: string
    sent: number
    opened: number
    unique_opened: number
    replied: number
    unique_replied: number
    bounced: number
    clicks: number
    unique_clicks: number
  }>
}

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

/**
 * Get daily analytics for Instantly campaigns
 *
 * Retrieves day-by-day engagement breakdown including sends, opens, replies,
 * bounces, and clicks. When no campaign_id is provided, returns aggregate
 * daily metrics across all campaigns in the workspace.
 *
 * @param credentials - Instantly API key
 * @param params - Optional campaign ID and date range
 * @param context - Execution context for logging
 * @returns Array of daily analytics entries
 */
export async function getDailyCampaignAnalytics(
  credentials: InstantlyCredentials,
  params: GetDailyCampaignAnalyticsParams,
  context?: ExecutionContext
): Promise<GetDailyCampaignAnalyticsResult> {
  const { apiKey } = credentials
  const { campaign_id, start_date, end_date } = params

  const queryParams = new URLSearchParams()
  if (campaign_id) 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 query = queryParams.toString()
  const url = `${INSTANTLY_API_BASE}/campaigns/analytics/daily${query ? `?${query}` : ''}`

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

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

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  const rawData = response.data ?? response
  const entries: Array<Record<string, unknown>> = Array.isArray(rawData) ? rawData : [rawData]

  const data = entries.map((entry) => ({
    date: String(entry.date ?? ''),
    sent: Number(entry.sent ?? 0),
    opened: Number(entry.opened ?? 0),
    unique_opened: Number(entry.unique_opened ?? 0),
    replied: Number(entry.replies ?? entry.replied ?? 0),
    unique_replied: Number(entry.unique_replies ?? entry.unique_replied ?? 0),
    bounced: Number(entry.bounced ?? 0),
    clicks: Number(entry.clicks ?? 0),
    unique_clicks: Number(entry.unique_clicks ?? 0)
  }))

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Daily campaign analytics fetched: campaign_id=${campaign_id} daily_entries=${data.length} executionId=${context.executionId}`
    )
  }

  return { data }
}
