import type { BaseIntegrationAdapter } from '../../../base-integration-adapter'
import { ToolingError } from '../../../../types'
import type { ExecutionContext } from '../../../../../base/types'
import { verifyEmail } from './fetch/verify-email/index'
import type { VerifyEmailParams } from './fetch/verify-email/index'
import { checkCredits } from './fetch/check-credits/index'

/**
 * MillionVerifier credentials format
 * Stored in credentials table, encrypted
 */
interface MillionVerifierCredentials {
  apiKey: string
}

/**
 * MillionVerifier integration adapter
 *
 * Provides access to the MillionVerifier email verification API for validating
 * email deliverability before campaigns. Uses API key as a query parameter.
 *
 * Credits are deducted for ok/invalid/disposable results; catch_all and unknown are free.
 *
 * @example
 * ```typescript
 * const adapter = new MillionVerifierAdapter()
 * const result = await adapter.call(
 *   'verifyEmail',
 *   { email: 'john@example.com' },
 *   { apiKey: 'your-api-key' },
 *   context
 * )
 * ```
 */
export class MillionVerifierAdapter implements BaseIntegrationAdapter {
  readonly name = 'millionverifier'

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

    // Safe to cast after validation confirms apiKey exists and is valid
    const creds = credentials as unknown as MillionVerifierCredentials

    // Route to method handler - delegate to fetch functions
    switch (method) {
      case 'verifyEmail':
        return verifyEmail(creds, params as VerifyEmailParams, context)
      case 'checkCredits':
        return checkCredits(creds, context)
      default:
        throw new ToolingError('method_not_found', `Unknown MillionVerifier method: ${method}`, {
          integration: this.name,
          method,
          organizationId: context?.organizationId
        })
    }
  }

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