import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { testConnector } from '@/lib/services/integration-service'

export const dynamic = 'force-dynamic'

/**
 * Test reachability without ingesting anything.
 *
 * A demo connector reports that its generator responded and that it reaches no external
 * system, in those words. A live connector with no endpoint reports unreachable — this
 * endpoint must never return success for a connection that does not exist.
 */
export const POST = apiRoute<{ code: string }>(
  { permission: 'integrations.sync', limit: 40 },
  async ({ params, user, request }) => {
    const result = await testConnector(params.code)
    if (!result) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.connectorTested,
      entity: 'integration_connector',
      entityId: params.code,
      user,
      request,
      detail: `${result.mode}: ${result.reachable ? 'reachable' : 'unreachable'}`,
    })

    return result
  },
)
