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 CreateCampaignParams {
  name: string
  sequences?: Array<{
    steps: Array<{
      type?: string
      delay?: number
      subject: string
      body: string
      variants?: Array<{
        subject: string
        body: string
      }>
    }>
  }>
  email_list?: string[]
  campaign_schedule?: {
    schedules: Array<{
      name: string
      timing: { from: string; to: string }
      days: Record<string, boolean>
      timezone: string
    }>
  }
  daily_limit?: number
  stop_on_reply?: boolean
  stop_on_auto_reply?: boolean
  track_opens?: boolean
  track_clicks?: boolean
  text_only?: boolean
}

export interface CreateCampaignResult {
  success: boolean
  campaign_id: string
  name: string
}

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

/**
 * Create a new Instantly campaign
 *
 * Creates a new campaign with optional sequences, email list, and sending configuration.
 * Returns the ID and name of the newly created campaign.
 *
 * @param credentials - Instantly API key
 * @param params - Campaign name (required) plus optional configuration
 * @param context - Execution context for logging
 * @returns Success status, campaign ID, and campaign name
 */
export async function createCampaign(
  credentials: InstantlyCredentials,
  params: CreateCampaignParams,
  context?: ExecutionContext
): Promise<CreateCampaignResult> {
  const { apiKey } = credentials
  const { name, ...optionalFields } = params

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

  const campaignsUrl = `${INSTANTLY_API_BASE}/campaigns`

  // Build request body from all provided fields
  const requestBody: Record<string, unknown> = { name }
  for (const [key, value] of Object.entries(optionalFields)) {
    if (value !== undefined) {
      requestBody[key] = value
    }
  }

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

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

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  const data = response.data ?? response
  const campaign_id = data.id || data.campaign_id || ''
  const campaignName = data.name || name

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

  return {
    success: true,
    campaign_id,
    name: campaignName
  }
}
