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 CreateInboxTestParams {
  email_account: string
  subject?: string
  body?: string
}

export interface CreateInboxTestResult {
  success: boolean
  test_id: string
  status: string
}

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

/**
 * Create an inbox placement test via Instantly
 *
 * Initiates an inbox placement test for the specified sending account.
 * The test checks deliverability across major email providers to diagnose
 * potential spam filtering or domain reputation issues.
 *
 * @param credentials - Instantly API key
 * @param params - Email account to test, optional subject and body
 * @param context - Execution context for logging
 * @returns Test ID and initial status
 */
export async function createInboxTest(
  credentials: InstantlyCredentials,
  params: CreateInboxTestParams,
  context?: ExecutionContext
): Promise<CreateInboxTestResult> {
  const { apiKey } = credentials
  const { email_account, subject, body } = params

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

  const inboxTestUrl = `${INSTANTLY_API_BASE}/inbox-placement-tests`

  const requestBody: Record<string, unknown> = {
    email_account
  }

  if (subject) {
    requestBody.subject = subject
  }

  if (body) {
    requestBody.body = body
  }

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Creating inbox placement test: email_account=${email_account} executionId=${context.executionId}`
    )
  }

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

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  const data = response.data ?? response
  const test_id = data.test_id || data.id || ''
  const status = data.status || 'pending'

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Inbox placement test created: email_account=${email_account} test_id=${test_id} status=${status} executionId=${context.executionId}`
    )
  }

  return {
    success: true,
    test_id,
    status
  }
}
