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

interface AnymailfinderCredentials {
  apiKey: string
}

export interface FindDecisionMakerEmailParams {
  domain?: string
  company_name?: string
  decision_maker_category: string[]
}

export interface FindDecisionMakerEmailResult {
  email: string
  email_status: 'valid' | 'risky' | 'not_found' | 'blacklisted'
  valid_email: string
  person_full_name: string
  person_job_title: string
  person_linkedin_url: string
  decision_maker_category: string
}

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

const _VALID_CATEGORIES = [
  'ceo',
  'operations',
  'marketing',
  'sales',
  'finance',
  'hr',
  'engineering',
  'it',
  'logistics',
  'buyer'
] as const

/**
 * Find a decision maker email via Anymailfinder
 *
 * Searches for the email address of a decision maker at a company, identified
 * by domain or company name, filtered by one or more role categories.
 *
 * @param credentials - Anymailfinder API key
 * @param params - Company identifier (domain or name) and decision maker categories
 * @param context - Execution context for logging
 * @returns Email address, status, and person details for the matched decision maker
 */
export async function findDecisionMakerEmail(
  credentials: AnymailfinderCredentials,
  params: FindDecisionMakerEmailParams,
  context?: ExecutionContext
): Promise<FindDecisionMakerEmailResult> {
  const { apiKey } = credentials
  const { domain, company_name, decision_maker_category } = params

  if (!domain && !company_name) {
    throw new ToolingError('validation_error', 'Either domain or company_name is required', {
      integration: 'anymailfinder',
      method: 'findDecisionMakerEmail'
    })
  }

  if (!decision_maker_category || decision_maker_category.length === 0) {
    throw new ToolingError('validation_error', 'decision_maker_category is required and must be non-empty', {
      integration: 'anymailfinder',
      method: 'findDecisionMakerEmail'
    })
  }

  const findUrl = `${ANYMAILFINDER_API_BASE}/find-email/decision-maker`

  if (context?.logger) {
    context.logger.info(
      `[AnymailfinderAdapter] Finding decision maker email: organizationId=${context.organizationId} executionId=${context.executionId} domain=${domain || 'none'} company_name=${company_name || 'none'} categories=${decision_maker_category.join(',')}`
    )
  }

  const response = await withRetry(async () => {
    const res = await fetch(findUrl, {
      method: 'POST',
      headers: {
        Authorization: apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        ...(domain ? { domain } : {}),
        ...(company_name ? { company_name } : {}),
        decision_maker_category
      }),
      signal: AbortSignal.timeout(180_000)
    })

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  if (context?.logger) {
    context.logger.info(
      `[AnymailfinderAdapter] Decision maker email fetched: organizationId=${context.organizationId} executionId=${context.executionId} email_status=${response.email_status ?? 'not_found'} category=${response.decision_maker_category ?? ''}`
    )
  }

  return {
    email: response.email ?? '',
    email_status: response.email_status ?? 'not_found',
    valid_email: response.valid_email ?? '',
    person_full_name: response.person_full_name ?? '',
    person_job_title: response.person_job_title ?? '',
    person_linkedin_url: response.person_linkedin_url ?? '',
    decision_maker_category: response.decision_maker_category ?? ''
  }
}
