import { withRetry, createHttpError, DEFAULT_RETRY_POLICY } from '../../../../../../../../../platform/resilience'
import type { ExecutionContext } from '../../../../../../../base/types'

interface InstantlyCredentials {
  apiKey: string
}

export interface PatchLeadParams {
  lead_id: string
  custom_variables: Record<string, string>
}

export interface PatchLeadResult {
  id: string
}

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

/**
 * Patch a lead's custom variables in Instantly
 *
 * Uses PATCH /api/v2/leads/{id} — custom_variables are merged additively,
 * so existing keys (e.g. opening_line) are preserved.
 *
 * @param credentials - Instantly API key
 * @param params - Lead ID and custom variables to set
 * @param context - Execution context for logging
 * @returns Object containing the updated lead's ID
 */
export async function patchLead(
  credentials: InstantlyCredentials,
  params: PatchLeadParams,
  context?: ExecutionContext
): Promise<PatchLeadResult> {
  const { apiKey } = credentials
  const { lead_id, custom_variables } = params

  const url = `${INSTANTLY_API_BASE}/leads/${lead_id}`

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Patching lead: lead_id=${lead_id} keys=[${Object.keys(custom_variables).join(', ')}] organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

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

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Lead patched: lead_id=${lead_id} organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

  return {
    id: String(response.id ?? lead_id)
  }
}
