/**
 * Attio List Notes - Native Fetch Implementation
 *
 * Lists notes attached to a specific Attio record using native Node.js fetch API.
 *
 * API Endpoint: GET /v2/notes?parent_object={object}&parent_record_id={recordId}
 * Documentation: https://docs.attio.com/rest-api/endpoint-reference/notes/list-notes
 */

import { ToolingError } from '../../../../../../types'
import type { ExecutionContext } from '../../../../../../../base/types'
import { withRetry, createHttpError, DEFAULT_RETRY_POLICY } from '../../../../../../../../../platform/resilience'
import type { AttioCredentials, ListNotesParams, ListNotesResult, AttioNotesListResponse } from '../utils/types'

/**
 * List notes attached to an Attio record
 *
 * @param credentials - Attio API credentials (apiKey)
 * @param params - Parent object and record ID to list notes for
 * @param context - Execution context for logging
 * @returns Array of notes with noteId, title, and createdAt
 * @throws ToolingError if listing fails
 */
export async function listNotes(
  credentials: AttioCredentials,
  params: ListNotesParams,
  context?: ExecutionContext
): Promise<ListNotesResult> {
  const { apiKey } = credentials
  const { parentObject, parentRecordId } = params

  if (!apiKey) {
    throw new ToolingError('credentials_invalid', 'Attio API credentials must include apiKey', {
      integration: 'attio',
      method: 'listNotes'
    })
  }

  if (!parentObject || !parentRecordId) {
    throw new ToolingError('validation_error', 'parentObject and parentRecordId are required', {
      integration: 'attio',
      method: 'listNotes',
      params: { parentObject, parentRecordId }
    })
  }

  const url = `https://api.attio.com/v2/notes?parent_object=${encodeURIComponent(parentObject)}&parent_record_id=${encodeURIComponent(parentRecordId)}`

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

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

      return res
    }, DEFAULT_RETRY_POLICY)

    const result = (await response.json()) as AttioNotesListResponse

    const notes = result.data.map((note) => ({
      noteId: note.id.note_id,
      title: note.title,
      createdAt: note.created_at
    }))

    if (context?.logger) {
      context.logger.info(
        `[AttioAdapter] Notes listed: parentObject=${parentObject} parentRecordId=${parentRecordId} count=${notes.length} executionId=${context.executionId}`
      )
    }

    return { notes, success: true }
  } catch (error) {
    if (error instanceof ToolingError) throw error

    throw new ToolingError('api_error', `Failed to list Attio notes: ${(error as Error).message}`, {
      integration: 'attio',
      method: 'listNotes',
      organizationId: context?.organizationId,
      params: { parentObject, parentRecordId },
      originalError: error
    })
  }
}
