/**
 * Attio Get Record - Native Fetch Implementation
 *
 * Fetches a single record by ID from an Attio object using native Node.js fetch API.
 * Supports all object types: people, companies, deals, and custom objects.
 *
 * API Endpoint: GET /v2/objects/{object}/records/{recordId}
 * Documentation: https://developers.attio.com/reference/get-record
 */

import { ToolingError } from '../../../../../../types'
import { withRetry, createHttpError, DEFAULT_RETRY_POLICY } from '../../../../../../../../../platform/resilience'
import type { ExecutionContext } from '../../../../../../../base/types'
import type { AttioCredentials, GetRecordParams, GetRecordResult, AttioRecordResponse } from '../utils/types'

/**
 * Get a single record by ID from an Attio object
 *
 * Uses native Node.js fetch API with retry logic for resilience.
 *
 * @param credentials - Attio API credentials (Bearer token)
 * @param params - Object type and record ID
 * @param context - Execution context for logging
 * @returns Record data with ID, values, createdAt, and webUrl
 * @throws ToolingError on API errors
 */
export async function getRecord(
  credentials: AttioCredentials,
  params: GetRecordParams,
  context?: ExecutionContext
): Promise<GetRecordResult> {
  const { object, recordId } = params
  const { apiKey } = credentials

  // Validate credentials
  if (!apiKey) {
    throw new ToolingError('credentials_invalid', 'Missing Attio API key', {
      integration: 'attio',
      method: 'getRecord'
    })
  }

  // Validate parameters
  if (!object || !recordId) {
    throw new ToolingError('validation_error', 'Missing required parameters: object and recordId', {
      integration: 'attio',
      method: 'getRecord',
      params: { object, recordId }
    })
  }

  // Build API URL
  const url = `https://api.attio.com/v2/objects/${object}/records/${recordId}`

  try {
    // Execute with retry logic
    const data = await withRetry(async () => {
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          Authorization: `Bearer ${apiKey}`,
          Accept: 'application/json'
        }
      })

      // Handle HTTP errors
      if (!response.ok) {
        throw await createHttpError(response, {
          integration: 'attio',
          method: 'getRecord',
          organizationId: context?.organizationId
        })
      }

      // Parse response
      const responseData = (await response.json()) as AttioRecordResponse

      // Validate response structure
      if (!responseData.data || !responseData.data.id || !responseData.data.id.record_id) {
        throw new ToolingError('api_error', 'Invalid response format: missing record ID', {
          integration: 'attio',
          method: 'getRecord',
          responseData
        })
      }

      return responseData
    }, DEFAULT_RETRY_POLICY)

    // Log success
    if (context?.logger) {
      context.logger.info(
        `[AttioAdapter] Record retrieved: object=${object} recordId=${data.data.id.record_id} executionId=${context.executionId}`
      )
    }

    // Transform to result format
    return {
      id: data.data.id.record_id,
      values: data.data.values,
      createdAt: data.data.created_at,
      webUrl: data.data.web_url
    }
  } catch (error) {
    // Re-throw ToolingError as-is
    if (error instanceof ToolingError) {
      throw error
    }

    // Wrap unknown errors
    throw new ToolingError('api_error', `Failed to get Attio record: ${(error as Error).message}`, {
      integration: 'attio',
      method: 'getRecord',
      organizationId: context?.organizationId,
      params: { object, recordId }
    })
  }
}
