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

interface InstantlyCredentials {
  apiKey: string
}

export interface ListCampaignsParams {
  limit?: number
  starting_after?: string
  search?: string
  status?: number
}

export interface ListCampaignsResult {
  campaigns: Array<{ id: string; name: string; status: string; created_at: string; [key: string]: unknown }>
  next_starting_after?: string
}

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

/**
 * List campaigns from Instantly workspace
 *
 * Retrieves a paginated list of campaigns with optional filtering by status or search term.
 * Uses cursor-based pagination via starting_after.
 *
 * @param credentials - Instantly API key
 * @param params - Pagination and filter options
 * @param context - Execution context for logging
 * @returns Campaigns array and optional next cursor for pagination
 */
export async function listCampaigns(
  credentials: InstantlyCredentials,
  params: ListCampaignsParams,
  context?: ExecutionContext
): Promise<ListCampaignsResult> {
  const { apiKey } = credentials
  const { limit, starting_after, search, status } = params

  const queryParams = new URLSearchParams()
  if (limit) queryParams.set('limit', String(limit))
  if (starting_after) queryParams.set('starting_after', starting_after)
  if (search) queryParams.set('search', search)
  if (status !== undefined) queryParams.set('status', String(status))

  const listUrl = `${INSTANTLY_API_BASE}/campaigns${queryParams.toString() ? `?${queryParams.toString()}` : ''}`

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Listing campaigns: limit=${limit} status=${status} executionId=${context.executionId}`
    )
  }

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

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  const rawData = response.data ?? response
  const campaigns = Array.isArray(rawData) ? rawData : rawData?.items || rawData?.campaigns || []
  const next_starting_after = response.next_starting_after || response.data?.next_starting_after

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Campaigns fetched: count=${campaigns.length} next=${next_starting_after || 'none'} organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

  return {
    campaigns,
    ...(next_starting_after ? { next_starting_after } : {})
  }
}
