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 GetCampaignParams {
  campaign_id: string
}

export interface GetCampaignResult {
  id: string
  name: string
  status: string
  sequences: unknown[]
  created_at: string
  [key: string]: unknown
}

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

/**
 * Get a specific campaign from Instantly by ID
 *
 * Retrieves full campaign details including sequences, status, and configuration.
 *
 * @param credentials - Instantly API key
 * @param params - Campaign ID to fetch
 * @param context - Execution context for logging
 * @returns Campaign details including sequences and metadata
 */
export async function getCampaign(
  credentials: InstantlyCredentials,
  params: GetCampaignParams,
  context?: ExecutionContext
): Promise<GetCampaignResult> {
  const { apiKey } = credentials
  const { campaign_id } = params

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

  const campaignUrl = `${INSTANTLY_API_BASE}/campaigns/${campaign_id}`

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

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

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  const campaign = response.data || response

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Campaign fetched: campaign_id=${campaign_id} name=${campaign.name} status=${campaign.status} executionId=${context.executionId}`
    )
  }

  return {
    id: campaign.id || campaign_id,
    name: campaign.name || '',
    status: campaign.status || '',
    sequences: campaign.sequences || [],
    created_at: campaign.created_at || '',
    ...campaign
  }
}
