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

interface AnymailfinderCredentials {
  apiKey: string
}

export interface FindPersonEmailParams {
  domain: string
  company_name?: string
  full_name?: string
  first_name?: string
  last_name?: string
}

export interface FindPersonEmailResult {
  email: string
  email_status: 'valid' | 'risky' | 'not_found' | 'blacklisted'
  valid_email: string
}

const ANYMAILFINDER_API_BASE = 'https://api.anymailfinder.com/v5.1'

/**
 * Find a person's email address via Anymailfinder
 *
 * Searches for a specific person's email by combining their name with a
 * company domain or name. Requires either full_name or first_name+last_name,
 * and either domain or company_name.
 *
 * @param credentials - Anymailfinder API key
 * @param params - Person name and company domain or name
 * @param context - Execution context for logging
 * @returns Email address, status, and validated email if available
 */
export async function findPersonEmail(
  credentials: AnymailfinderCredentials,
  params: FindPersonEmailParams,
  context?: ExecutionContext
): Promise<FindPersonEmailResult> {
  const { apiKey } = credentials

  if (!params.domain && !params.company_name) {
    throw new Error('Either domain or company_name is required for findPersonEmail')
  }

  if (!params.full_name && !(params.first_name && params.last_name)) {
    throw new Error('Either full_name or both first_name and last_name are required for findPersonEmail')
  }

  if (context?.logger) {
    context.logger.info(
      `[AnymailfinderAdapter] findPersonEmail: organizationId=${context.organizationId} executionId=${context.executionId} domain=${params.domain} company_name=${params.company_name} full_name=${params.full_name} first_name=${params.first_name} last_name=${params.last_name}`
    )
  }

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

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  if (context?.logger) {
    context.logger.info(
      `[AnymailfinderAdapter] findPersonEmail complete: organizationId=${context.organizationId} email_status=${response.email_status} email=${response.email ? '[found]' : '[not found]'}`
    )
  }

  return {
    email: response.email ?? '',
    email_status: response.email_status ?? 'not_found',
    valid_email: response.valid_email ?? ''
  }
}
