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

/**
 * Create a new record in an Attio object using native fetch API
 *
 * @param credentials - Attio API credentials (apiKey)
 * @param params - Record creation parameters (object type and field values)
 * @param context - Execution context for logging
 * @returns Created record ID and success status
 * @throws ToolingError if record creation fails
 *
 * @example
 * // Create a person record
 * const person = await createRecord(
 *   { apiKey: 'xxx' },
 *   {
 *     object: 'people',
 *     values: {
 *       name: {
 *         first_name: 'John',
 *         last_name: 'Doe',
 *         full_name: 'John Doe'
 *       },
 *       email_addresses: [
 *         { email_address: 'john@example.com' }
 *       ]
 *     }
 *   },
 *   context
 * )
 *
 * @example
 * // Create a company record
 * const company = await createRecord(
 *   { apiKey: 'xxx' },
 *   {
 *     object: 'companies',
 *     values: {
 *       name: 'Acme Corp',
 *       domains: [{ domain: 'acme.com' }]
 *     }
 *   },
 *   context
 * )
 */
export async function createRecord(
  credentials: AttioCredentials,
  params: CreateRecordParams,
  context?: ExecutionContext
): Promise<CreateRecordResult> {
  const { apiKey } = credentials
  const { object, values } = params

  // Validate required parameters
  if (!apiKey) {
    throw new ToolingError('credentials_invalid', 'Attio API credentials must include apiKey', {
      integration: 'attio',
      method: 'createRecord'
    })
  }

  if (!object || !values) {
    throw new ToolingError('validation_error', 'Object type and values are required', {
      integration: 'attio',
      method: 'createRecord',
      params: { object, values }
    })
  }

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

  // Build request body with nested data.values structure (CRITICAL!)
  const requestBody = {
    data: {
      values
    }
  }

  try {
    // Execute with retry logic
    const response = await withRetry(async () => {
      const res = await fetch(url, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${apiKey}`,
          'Content-Type': 'application/json',
          Accept: 'application/json'
        },
        body: JSON.stringify(requestBody)
      })

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

      return res
    }, DEFAULT_RETRY_POLICY)

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

    // Extract record ID from nested structure
    const recordId = result.data.id.record_id

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

    // Return standardized 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 create Attio record: ${(error as Error).message}`, {
      integration: 'attio',
      method: 'createRecord',
      organizationId: context?.organizationId,
      params: { object },
      originalError: error
    })
  }
}
