import type { BaseIntegrationAdapter } from '../../../base-integration-adapter'
import { ToolingError } from '../../../../types'
import type { ExecutionContext } from '../../../../../base/types'

import { findCompanyEmail } from './fetch/find-company-email/index'
import type { FindCompanyEmailParams } from './fetch/find-company-email/index'
import { findPersonEmail } from './fetch/find-person-email/index'
import type { FindPersonEmailParams } from './fetch/find-person-email/index'
import { findDecisionMakerEmail } from './fetch/find-decision-maker-email/index'
import type { FindDecisionMakerEmailParams } from './fetch/find-decision-maker-email/index'
import { verifyEmail } from './fetch/verify-email/index'
import type { VerifyEmailParams } from './fetch/verify-email/index'

interface AnymailfinderCredentials {
  apiKey: string
}

/**
 * Anymailfinder integration adapter
 *
 * Provides access to the Anymailfinder email discovery API for finding and
 * verifying email addresses by company domain, person name, or decision maker role.
 *
 * @example
 * const adapter = new AnymailfinderAdapter()
 * const result = await adapter.call(
 *   'findCompanyEmail',
 *   { domain: 'example.com' },
 *   { apiKey: 'anymailfinder_api_...' },
 *   context
 * )
 */
export class AnymailfinderAdapter implements BaseIntegrationAdapter {
  readonly name = 'anymailfinder'

  async call(
    method: string,
    params: unknown,
    credentials: Record<string, unknown>,
    context?: ExecutionContext
  ): Promise<unknown> {
    if (!this.validateCredentials(credentials)) {
      throw new ToolingError('credentials_invalid', 'Invalid Anymailfinder credentials', {
        integration: this.name,
        organizationId: context?.organizationId
      })
    }

    const creds = credentials as unknown as AnymailfinderCredentials

    switch (method) {
      case 'findCompanyEmail':
        return findCompanyEmail(creds, params as FindCompanyEmailParams, context)
      case 'findPersonEmail':
        return findPersonEmail(creds, params as FindPersonEmailParams, context)
      case 'findDecisionMakerEmail':
        return findDecisionMakerEmail(creds, params as FindDecisionMakerEmailParams, context)
      case 'verifyEmail':
        return verifyEmail(creds, params as VerifyEmailParams, context)
      default:
        throw new ToolingError('method_not_found', `Unknown Anymailfinder method: ${method}`, {
          integration: this.name,
          method,
          organizationId: context?.organizationId
        })
    }
  }

  validateCredentials(credentials: Record<string, unknown>): boolean {
    const creds = credentials as unknown as AnymailfinderCredentials
    return !!creds.apiKey && typeof creds.apiKey === 'string' && creds.apiKey.length > 0
  }
}
