/**
 * Attio Delete Record - Native Fetch Implementation
 *
 * Deletes 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: DELETE /v2/objects/{object}/records/{recordId}
 * Documentation: https://docs.attio.com/rest-api/endpoint-reference/records/delete-a-record
 */

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

/**
 * Delete 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 Success status with deleted record ID
 * @throws ToolingError on API errors
 */
export async function deleteRecord(
  credentials: AttioCredentials,
  params: DeleteRecordParams,
  context?: ExecutionContext
): Promise<DeleteRecordResult> {
  const { object, recordId } = params
  const { apiKey } = credentials

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

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

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

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

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

      // Successful deletion returns empty object {}
      return await response.json()
    }, DEFAULT_RETRY_POLICY)

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

    // Return success result
    return {
      recordId,
      success: true
    }
  } catch (error) {
    // Re-throw ToolingError as-is
    if (error instanceof ToolingError) {
      throw error
    }

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