/**
 * Attio Delete Note - Native Fetch Implementation
 *
 * Deletes a single note by ID using native Node.js fetch API.
 *
 * API Endpoint: DELETE /v2/notes/{noteId}
 * Documentation: https://docs.attio.com/rest-api/endpoint-reference/notes/delete-a-note
 */

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

/**
 * Delete a note by ID from Attio
 *
 * @param credentials - Attio API credentials (apiKey)
 * @param params - Note ID to delete
 * @param context - Execution context for logging
 * @returns Deleted note ID and success status
 * @throws ToolingError if deletion fails
 */
export async function deleteNote(
  credentials: AttioCredentials,
  params: DeleteNoteParams,
  context?: ExecutionContext
): Promise<DeleteNoteResult> {
  const { apiKey } = credentials
  const { noteId } = params

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

  if (!noteId) {
    throw new ToolingError('validation_error', 'noteId is required', {
      integration: 'attio',
      method: 'deleteNote',
      params: { noteId }
    })
  }

  const url = `https://api.attio.com/v2/notes/${encodeURIComponent(noteId)}`

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

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

      return await response.json()
    }, DEFAULT_RETRY_POLICY)

    if (context?.logger) {
      context.logger.info(`[AttioAdapter] Note deleted: noteId=${noteId} executionId=${context.executionId}`)
    }

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

    throw new ToolingError('api_error', `Failed to delete Attio note: ${(error as Error).message}`, {
      integration: 'attio',
      method: 'deleteNote',
      organizationId: context?.organizationId,
      params: { noteId },
      originalError: error
    })
  }
}
