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

export interface PauseCampaignResult {
  success: boolean
  campaign_id: string
}

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

/**
 * Pause an active Instantly campaign
 *
 * Pauses a running campaign, stopping further email sends until the campaign is activated again.
 * Leads already in progress are not affected until the next scheduled send.
 *
 * @param credentials - Instantly API key
 * @param params - Campaign ID to pause
 * @param context - Execution context for logging
 * @returns Success status and campaign ID
 */
export async function pauseCampaign(
  credentials: InstantlyCredentials,
  params: PauseCampaignParams,
  context?: ExecutionContext
): Promise<PauseCampaignResult> {
  const { apiKey } = credentials
  const { campaign_id } = params

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

  const pauseUrl = `${INSTANTLY_API_BASE}/campaigns/${campaign_id}/pause`

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

  await withRetry(async () => {
    const res = await fetch(pauseUrl, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({})
    })

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Campaign paused successfully: campaign_id=${campaign_id} organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

  return {
    success: true,
    campaign_id
  }
}
