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

export interface ActivateCampaignResult {
  success: boolean
  campaign_id: string
}

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

/**
 * Activate a paused or draft Instantly campaign
 *
 * Activates a campaign so it begins (or resumes) sending emails to leads.
 * A campaign must be activated before any emails are sent.
 *
 * @param credentials - Instantly API key
 * @param params - Campaign ID to activate
 * @param context - Execution context for logging
 * @returns Success status and campaign ID
 */
export async function activateCampaign(
  credentials: InstantlyCredentials,
  params: ActivateCampaignParams,
  context?: ExecutionContext
): Promise<ActivateCampaignResult> {
  const { apiKey } = credentials
  const { campaign_id } = params

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

  const activateUrl = `${INSTANTLY_API_BASE}/campaigns/${campaign_id}/activate`

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

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

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

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

  return {
    success: true,
    campaign_id
  }
}
