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

interface MillionVerifierCredentials {
  apiKey: string
}

const MV_CREDITS_URL = 'https://api.millionverifier.com/api/v3/credits'

/**
 * Check remaining MillionVerifier credits
 *
 * @param credentials - MillionVerifier API key
 * @param context - Execution context for logging
 * @returns Credit balance breakdown
 */
export async function checkCredits(
  credentials: MillionVerifierCredentials,
  context?: ExecutionContext
): Promise<MillionVerifierCheckCreditsResult> {
  const { apiKey } = credentials

  if (context?.logger) {
    context.logger.info(
      `[MillionVerifierAdapter] checkCredits: organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

  const url = new URL(MV_CREDITS_URL)
  url.searchParams.set('api', apiKey)

  const response = await withRetry(async () => {
    const res = await fetch(url.toString(), {
      method: 'GET',
      signal: AbortSignal.timeout(30_000)
    })

    if (!res.ok) {
      throw new ToolingError('api_error', `MillionVerifier credits API returned HTTP ${res.status}`, {
        integration: 'millionverifier',
        method: 'checkCredits',
        organizationId: context?.organizationId
      })
    }

    return res.json() as Promise<Record<string, unknown>>
  }, DEFAULT_RETRY_POLICY)

  const data = response as Record<string, unknown>

  return {
    credits: (data.credits as number) ?? 0,
    bulkCredits: (data.bulk_credits as number) ?? 0,
    renewingCredits: (data.renewing_credits as number) ?? 0,
    plan: (data.plan as number) ?? 0
  }
}
