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 UpdateCampaignParams {
  campaign_id: string
  name?: string
  sequences?: unknown[]
  daily_limit?: number
  stop_on_reply?: boolean
  [key: string]: unknown
}

export interface UpdateCampaignResult {
  success: boolean
  campaign_id: string
}

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

/**
 * Update an existing Instantly campaign
 *
 * Applies a partial update (PATCH) to a campaign. Only provided fields are updated.
 * Supports updating name, sequences, sending limits, and reply handling.
 *
 * @param credentials - Instantly API key
 * @param params - Campaign ID (required) plus optional fields to update
 * @param context - Execution context for logging
 * @returns Success status and campaign ID
 */
export async function updateCampaign(
  credentials: InstantlyCredentials,
  params: UpdateCampaignParams,
  context?: ExecutionContext
): Promise<UpdateCampaignResult> {
  const { apiKey } = credentials
  const { campaign_id, ...updateFields } = params

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

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

  // Build the PATCH body from remaining fields, excluding undefined values
  const requestBody: Record<string, unknown> = {}
  for (const [key, value] of Object.entries(updateFields)) {
    if (value !== undefined) {
      requestBody[key] = value
    }
  }

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Updating campaign: campaign_id=${campaign_id} fields=${Object.keys(requestBody).join(',')} organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

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

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

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

  return {
    success: true,
    campaign_id
  }
}
